/* Generated from 'MathContext.nrx' 8 Sep 2000 11:07:48 [v2.00] */
/* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
//--package com.ibm.icu.math;

/* ------------------------------------------------------------------ */
/* MathContext -- Math context settings                               */
/* ------------------------------------------------------------------ */
/* Copyright IBM Corporation, 1997, 2000.  All Rights Reserved.       */
/*                                                                    */
/*   The MathContext object encapsulates the settings used by the     */
/*   BigDecimal class; it could also be used by other arithmetics.    */
/* ------------------------------------------------------------------ */
/* Notes:                                                             */
/*                                                                    */
/* 1. The properties are checked for validity on construction, so     */
/*    the BigDecimal class may assume that they are correct.          */
/* ------------------------------------------------------------------ */
/* Author:    Mike Cowlishaw                                          */
/* 1997.09.03 Initial version (edited from netrexx.lang.RexxSet)      */
/* 1997.09.12 Add lostDigits property                                 */
/* 1998.05.02 Make the class immutable and final; drop set methods    */
/* 1998.06.05 Add Round (rounding modes) property                     */
/* 1998.06.25 Rename from DecimalContext; allow digits=0              */
/* 1998.10.12 change to com.ibm.icu.math package                          */
/* 1999.02.06 add javadoc comments                                    */
/* 1999.03.05 simplify; changes from discussion with J. Bloch         */
/* 1999.03.13 1.00 release to IBM Centre for Java Technology          */
/* 1999.07.10 1.04 flag serialization unused                          */
/* 2000.01.01 1.06 copyright update                                   */
/* ------------------------------------------------------------------ */


/* JavaScript conversion (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany */



/**
 * The <code>MathContext</code> immutable class encapsulates the
 * settings understood by the operator methods of the {@link BigDecimal}
 * class (and potentially other classes).  Operator methods are those
 * that effect an operation on a number or a pair of numbers.
 * <p>
 * The settings, which are not base-dependent, comprise:
 * <ol>
 * <li><code>digits</code>:
 * the number of digits (precision) to be used for an operation
 * <li><code>form</code>:
 * the form of any exponent that results from the operation
 * <li><code>lostDigits</code>:
 * whether checking for lost digits is enabled
 * <li><code>roundingMode</code>:
 * the algorithm to be used for rounding.
 * </ol>
 * <p>
 * When provided, a <code>MathContext</code> object supplies the
 * settings for an operation directly.
 * <p>
 * When <code>MathContext.DEFAULT</code> is provided for a
 * <code>MathContext</code> parameter then the default settings are used
 * (<code>9, SCIENTIFIC, false, ROUND_HALF_UP</code>).
 * <p>
 * In the <code>BigDecimal</code> class, all methods which accept a
 * <code>MathContext</code> object defaults) also have a version of the
 * method which does not accept a MathContext parameter.  These versions
 * carry out unlimited precision fixed point arithmetic (as though the
 * settings were (<code>0, PLAIN, false, ROUND_HALF_UP</code>).
 * <p>
 * The instance variables are shared with default access (so they are
 * directly accessible to the <code>BigDecimal</code> class), but must
 * never be changed.
 * <p>
 * The rounding mode constants have the same names and values as the
 * constants of the same name in <code>java.math.BigDecimal</code>, to
 * maintain compatibility with earlier versions of
 * <code>BigDecimal</code>.
 *
 * @see     BigDecimal
 * @author  Mike Cowlishaw
 * @stable ICU 2.0
 */

//--public final class MathContext implements java.io.Serializable{
 //--private static final java.lang.String $0="MathContext.nrx";
 
 //-- methods
 MathContext.prototype.getDigits = getDigits;
 MathContext.prototype.getForm = getForm;
 MathContext.prototype.getLostDigits = getLostDigits;
 MathContext.prototype.getRoundingMode = getRoundingMode;
 MathContext.prototype.toString = toString;
 MathContext.prototype.isValidRound = isValidRound;

 
 /* ----- Properties ----- */
 /* properties public constant */
 /**
  * Plain (fixed point) notation, without any exponent.
  * Used as a setting to control the form of the result of a
  * <code>BigDecimal</code> operation.
  * A zero result in plain form may have a decimal part of one or
  * more zeros.
  *
  * @see #ENGINEERING
  * @see #SCIENTIFIC
  * @stable ICU 2.0
  */
 //--public static final int PLAIN=0; // [no exponent]
 MathContext.prototype.PLAIN=0; // [no exponent]
 
 /**
  * Standard floating point notation (with scientific exponential
  * format, where there is one digit before any decimal point).
  * Used as a setting to control the form of the result of a
  * <code>BigDecimal</code> operation.
  * A zero result in plain form may have a decimal part of one or
  * more zeros.
  *
  * @see #ENGINEERING
  * @see #PLAIN
  * @stable ICU 2.0
  */
 //--public static final int SCIENTIFIC=1; // 1 digit before .
 MathContext.prototype.SCIENTIFIC=1; // 1 digit before .
 
 /**
  * Standard floating point notation (with engineering exponential
  * format, where the power of ten is a multiple of 3).
  * Used as a setting to control the form of the result of a
  * <code>BigDecimal</code> operation.
  * A zero result in plain form may have a decimal part of one or
  * more zeros.
  *
  * @see #PLAIN
  * @see #SCIENTIFIC
  * @stable ICU 2.0
  */
 //--public static final int ENGINEERING=2; // 1-3 digits before .
 MathContext.prototype.ENGINEERING=2; // 1-3 digits before .
 
 // The rounding modes match the original BigDecimal class values
 /**
  * Rounding mode to round to a more positive number.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * If any of the discarded digits are non-zero then the result
  * should be rounded towards the next more positive digit.
  * @stable ICU 2.0
  */
 //--public static final int ROUND_CEILING=2;
 MathContext.prototype.ROUND_CEILING=2;
 
 /**
  * Rounding mode to round towards zero.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * All discarded digits are ignored (truncated).  The result is
  * neither incremented nor decremented.
  * @stable ICU 2.0
  */
 //--public static final int ROUND_DOWN=1;
 MathContext.prototype.ROUND_DOWN=1;
 
 /**
  * Rounding mode to round to a more negative number.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * If any of the discarded digits are non-zero then the result
  * should be rounded towards the next more negative digit.
  * @stable ICU 2.0
  */
 //--public static final int ROUND_FLOOR=3;
 MathContext.prototype.ROUND_FLOOR=3;
 
 /**
  * Rounding mode to round to nearest neighbor, where an equidistant
  * value is rounded down.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * If the discarded digits represent greater than half (0.5 times)
  * the value of a one in the next position then the result should be
  * rounded up (away from zero).  Otherwise the discarded digits are
  * ignored.
  * @stable ICU 2.0
  */
 //--public static final int ROUND_HALF_DOWN=5;
 MathContext.prototype.ROUND_HALF_DOWN=5;
 
 /**
  * Rounding mode to round to nearest neighbor, where an equidistant
  * value is rounded to the nearest even neighbor.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * If the discarded digits represent greater than half (0.5 times)
  * the value of a one in the next position then the result should be
  * rounded up (away from zero).  If they represent less than half,
  * then the result should be rounded down.
  * <p>
  * Otherwise (they represent exactly half) the result is rounded
  * down if its rightmost digit is even, or rounded up if its
  * rightmost digit is odd (to make an even digit).
  * @stable ICU 2.0
  */
 //--public static final int ROUND_HALF_EVEN=6;
 MathContext.prototype.ROUND_HALF_EVEN=6;
 
 /**
  * Rounding mode to round to nearest neighbor, where an equidistant
  * value is rounded up.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * If the discarded digits represent greater than or equal to half
  * (0.5 times) the value of a one in the next position then the result
  * should be rounded up (away from zero).  Otherwise the discarded
  * digits are ignored.
  * @stable ICU 2.0
  */
 //--public static final int ROUND_HALF_UP=4;
 MathContext.prototype.ROUND_HALF_UP=4;
 
 /**
  * Rounding mode to assert that no rounding is necessary.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * Rounding (potential loss of information) is not permitted.
  * If any of the discarded digits are non-zero then an
  * <code>ArithmeticException</code> should be thrown.
  * @stable ICU 2.0
  */
 //--public static final int ROUND_UNNECESSARY=7;
 MathContext.prototype.ROUND_UNNECESSARY=7;
 
 /**
  * Rounding mode to round away from zero.
  * Used as a setting to control the rounding mode used during a
  * <code>BigDecimal</code> operation.
  * <p>
  * If any of the discarded digits are non-zero then the result will
  * be rounded up (away from zero).
  * @stable ICU 2.0
  */
 //--public static final int ROUND_UP=0;
 MathContext.prototype.ROUND_UP=0;
 
 
 /* properties shared */
 /**
  * The number of digits (precision) to be used for an operation.
  * A value of 0 indicates that unlimited precision (as many digits
  * as are required) will be used.
  * <p>
  * The {@link BigDecimal} operator methods use this value to
  * determine the precision of results.
  * Note that leading zeros (in the integer part of a number) are
  * never significant.
  * <p>
  * <code>digits</code> will always be non-negative.
  *
  * @serial
  */
 //--int digits;
 
 /**
  * The form of results from an operation.
  * <p>
  * The {@link BigDecimal} operator methods use this value to
  * determine the form of results, in particular whether and how
  * exponential notation should be used.
  *
  * @see #ENGINEERING
  * @see #PLAIN
  * @see #SCIENTIFIC
  * @serial
  */
 //--int form; // values for this must fit in a byte
 
 /**
  * Controls whether lost digits checking is enabled for an
  * operation.
  * Set to <code>true</code> to enable checking, or
  * to <code>false</code> to disable checking.
  * <p>
  * When enabled, the {@link BigDecimal} operator methods check
  * the precision of their operand or operands, and throw an
  * <code>ArithmeticException</code> if an operand is more precise
  * than the digits setting (that is, digits would be lost).
  * When disabled, operands are rounded to the specified digits.
  *
  * @serial
  */
 //--boolean lostDigits;
 
 /**
  * The rounding algorithm to be used for an operation.
  * <p>
  * The {@link BigDecimal} operator methods use this value to
  * determine the algorithm to be used when non-zero digits have to
  * be discarded in order to reduce the precision of a result.
  * The value must be one of the public constants whose name starts
  * with <code>ROUND_</code>.
  *
  * @see #ROUND_CEILING
  * @see #ROUND_DOWN
  * @see #ROUND_FLOOR
  * @see #ROUND_HALF_DOWN
  * @see #ROUND_HALF_EVEN
  * @see #ROUND_HALF_UP
  * @see #ROUND_UNNECESSARY
  * @see #ROUND_UP
  * @serial
  */
 //--int roundingMode;
 
 /* properties private constant */
 // default settings
 //--private static final int DEFAULT_FORM=SCIENTIFIC;
 //--private static final int DEFAULT_DIGITS=9;
 //--private static final boolean DEFAULT_LOSTDIGITS=false;
 //--private static final int DEFAULT_ROUNDINGMODE=ROUND_HALF_UP;
 MathContext.prototype.DEFAULT_FORM=MathContext.prototype.SCIENTIFIC;
 MathContext.prototype.DEFAULT_DIGITS=9;
 MathContext.prototype.DEFAULT_LOSTDIGITS=false;
 MathContext.prototype.DEFAULT_ROUNDINGMODE=MathContext.prototype.ROUND_HALF_UP;
 
 /* properties private constant */
 
 //--private static final int MIN_DIGITS=0; // smallest value for DIGITS.
 //--private static final int MAX_DIGITS=999999999; // largest value for DIGITS.  If increased,
 MathContext.prototype.MIN_DIGITS=0; // smallest value for DIGITS.
 MathContext.prototype.MAX_DIGITS=999999999; // largest value for DIGITS.  If increased,
 // the BigDecimal class may need update.
 // list of valid rounding mode values, most common two first
 //--private static final int ROUNDS[]=new int[]{ROUND_HALF_UP,ROUND_UNNECESSARY,ROUND_CEILING,ROUND_DOWN,ROUND_FLOOR,ROUND_HALF_DOWN,ROUND_HALF_EVEN,ROUND_UP};
 MathContext.prototype.ROUNDS=new Array(MathContext.prototype.ROUND_HALF_UP,MathContext.prototype.ROUND_UNNECESSARY,MathContext.prototype.ROUND_CEILING,MathContext.prototype.ROUND_DOWN,MathContext.prototype.ROUND_FLOOR,MathContext.prototype.ROUND_HALF_DOWN,MathContext.prototype.ROUND_HALF_EVEN,MathContext.prototype.ROUND_UP);
 
 
 //--private static final java.lang.String ROUNDWORDS[]=new java.lang.String[]{"ROUND_HALF_UP","ROUND_UNNECESSARY","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_UP"}; // matching names of the ROUNDS values
 MathContext.prototype.ROUNDWORDS=new Array("ROUND_HALF_UP","ROUND_UNNECESSARY","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_UP"); // matching names of the ROUNDS values
 
 
 
 
 /* properties private constant unused */
 
 // Serialization version
 //--private static final long serialVersionUID=7163376998892515376L;
 
 /* properties public constant */
 /**
  * A <code>MathContext</code> object initialized to the default
  * settings for general-purpose arithmetic.  That is,
  * <code>digits=9 form=SCIENTIFIC lostDigits=false
  * roundingMode=ROUND_HALF_UP</code>.
  *
  * @see #SCIENTIFIC
  * @see #ROUND_HALF_UP
  * @stable ICU 2.0
  */
 //--public static final com.ibm.icu.math.MathContext DEFAULT=new com.ibm.icu.math.MathContext(DEFAULT_DIGITS,DEFAULT_FORM,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
 MathContext.prototype.DEFAULT=new MathContext(MathContext.prototype.DEFAULT_DIGITS,MathContext.prototype.DEFAULT_FORM,MathContext.prototype.DEFAULT_LOSTDIGITS,MathContext.prototype.DEFAULT_ROUNDINGMODE);

 
 
 
 /* ----- Constructors ----- */
 
 /**
  * Constructs a new <code>MathContext</code> with a specified
  * precision.
  * The other settings are set to the default values
  * (see {@link #DEFAULT}).
  *
  * An <code>IllegalArgumentException</code> is thrown if the
  * <code>setdigits</code> parameter is out of range
  * (&lt;0 or &gt;999999999).
  *
  * @param setdigits     The <code>int</code> digits setting
  *                      for this <code>MathContext</code>.
  * @throws IllegalArgumentException parameter out of range.
  * @stable ICU 2.0
  */
 
 //--public MathContext(int setdigits){
 //-- this(setdigits,DEFAULT_FORM,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
 //-- return;}

 
 /**
  * Constructs a new <code>MathContext</code> with a specified
  * precision and form.
  * The other settings are set to the default values
  * (see {@link #DEFAULT}).
  *
  * An <code>IllegalArgumentException</code> is thrown if the
  * <code>setdigits</code> parameter is out of range
  * (&lt;0 or &gt;999999999), or if the value given for the
  * <code>setform</code> parameter is not one of the appropriate
  * constants.
  *
  * @param setdigits     The <code>int</code> digits setting
  *                      for this <code>MathContext</code>.
  * @param setform       The <code>int</code> form setting
  *                      for this <code>MathContext</code>.
  * @throws IllegalArgumentException parameter out of range.
  * @stable ICU 2.0
  */
 
 //--public MathContext(int setdigits,int setform){
 //-- this(setdigits,setform,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
 //-- return;}

 /**
  * Constructs a new <code>MathContext</code> with a specified
  * precision, form, and lostDigits setting.
  * The roundingMode setting is set to its default value
  * (see {@link #DEFAULT}).
  *
  * An <code>IllegalArgumentException</code> is thrown if the
  * <code>setdigits</code> parameter is out of range
  * (&lt;0 or &gt;999999999), or if the value given for the
  * <code>setform</code> parameter is not one of the appropriate
  * constants.
  *
  * @param setdigits     The <code>int</code> digits setting
  *                      for this <code>MathContext</code>.
  * @param setform       The <code>int</code> form setting
  *                      for this <code>MathContext</code>.
  * @param setlostdigits The <code>boolean</code> lostDigits
  *                      setting for this <code>MathContext</code>.
  * @throws IllegalArgumentException parameter out of range.
  * @stable ICU 2.0
  */
 
 //--public MathContext(int setdigits,int setform,boolean setlostdigits){
 //-- this(setdigits,setform,setlostdigits,DEFAULT_ROUNDINGMODE);
 //-- return;}

 /**
  * Constructs a new <code>MathContext</code> with a specified
  * precision, form, lostDigits, and roundingMode setting.
  *
  * An <code>IllegalArgumentException</code> is thrown if the
  * <code>setdigits</code> parameter is out of range
  * (&lt;0 or &gt;999999999), or if the value given for the
  * <code>setform</code> or <code>setroundingmode</code> parameters is
  * not one of the appropriate constants.
  *
  * @param setdigits       The <code>int</code> digits setting
  *                        for this <code>MathContext</code>.
  * @param setform         The <code>int</code> form setting
  *                        for this <code>MathContext</code>.
  * @param setlostdigits   The <code>boolean</code> lostDigits
  *                        setting for this <code>MathContext</code>.
  * @param setroundingmode The <code>int</code> roundingMode setting
  *                        for this <code>MathContext</code>.
  * @throws IllegalArgumentException parameter out of range.
  * @stable ICU 2.0
  */
 
 //--public MathContext(int setdigits,int setform,boolean setlostdigits,int setroundingmode){super();
 function MathContext() {
  //-- members
  this.digits = 0;
  this.form = 0; // values for this must fit in a byte
  this.lostDigits = false;
  this.roundingMode = 0;

  //-- overloaded ctor
  var setform = this.DEFAULT_FORM;
  var setlostdigits = this.DEFAULT_LOSTDIGITS;
  var setroundingmode = this.DEFAULT_ROUNDINGMODE;
  if (MathContext.arguments.length == 4)
   {
    setform = MathContext.arguments[1];
    setlostdigits = MathContext.arguments[2];
    setroundingmode = MathContext.arguments[3];
   }
  else if (MathContext.arguments.length == 3)
   {
    setform = MathContext.arguments[1];
    setlostdigits = MathContext.arguments[2];
   }
  else if (MathContext.arguments.length == 2)
   {
    setform = MathContext.arguments[1];
   }
  else if (MathContext.arguments.length != 1)
   {
    throw "MathContext(): " + MathContext.arguments.length + " arguments given; expected 1 to 4"
   }
  var setdigits = MathContext.arguments[0];
  
  
  // set values, after checking
  if (setdigits!=this.DEFAULT_DIGITS) 
   {
    if (setdigits<this.MIN_DIGITS) 
     throw "MathContext(): Digits too small: "+setdigits;
    if (setdigits>this.MAX_DIGITS) 
     throw "MathContext(): Digits too large: "+setdigits;
   }
  {/*select*/
  if (setform==this.SCIENTIFIC)
   ; // [most common]
  else if (setform==this.ENGINEERING)
   ;
  else if (setform==this.PLAIN)
   ;
  else{
   throw "MathContext() Bad form value: "+setform;
  }
  }
  if ((!(this.isValidRound(setroundingmode)))) 
   throw "MathContext(): Bad roundingMode value: "+setroundingmode;
  this.digits=setdigits;
  this.form=setform;
  this.lostDigits=setlostdigits; // [no bad value possible]
  this.roundingMode=setroundingmode;
  return;}

 /**
  * Returns the digits setting.
  * This value is always non-negative.
  *
  * @return an <code>int</code> which is the value of the digits
  *         setting
  * @stable ICU 2.0
  */
 
 //--public int getDigits(){
 function getDigits() {
  return this.digits;
  }

 /**
  * Returns the form setting.
  * This will be one of
  * {@link #ENGINEERING},
  * {@link #PLAIN}, or
  * {@link #SCIENTIFIC}.
  *
  * @return an <code>int</code> which is the value of the form setting
  * @stable ICU 2.0
  */
 
 //--public int getForm(){
 function getForm() {
  return this.form;
  }

 /**
  * Returns the lostDigits setting.
  * This will be either <code>true</code> (enabled) or
  * <code>false</code> (disabled).
  *
  * @return a <code>boolean</code> which is the value of the lostDigits
  *           setting
  * @stable ICU 2.0
  */
 
 //--public boolean getLostDigits(){
 function getLostDigits() {
  return this.lostDigits;
  }

 /**
  * Returns the roundingMode setting.
  * This will be one of
  * {@link  #ROUND_CEILING},
  * {@link  #ROUND_DOWN},
  * {@link  #ROUND_FLOOR},
  * {@link  #ROUND_HALF_DOWN},
  * {@link  #ROUND_HALF_EVEN},
  * {@link  #ROUND_HALF_UP},
  * {@link  #ROUND_UNNECESSARY}, or
  * {@link  #ROUND_UP}.
  *
  * @return an <code>int</code> which is the value of the roundingMode
  *         setting
  * @stable ICU 2.0
  */
 
 //--public int getRoundingMode(){
 function getRoundingMode() {
  return this.roundingMode;
  }

 /** Returns the <code>MathContext</code> as a readable string.
  * The <code>String</code> returned represents the settings of the
  * <code>MathContext</code> object as four blank-delimited words
  * separated by a single blank and with no leading or trailing blanks,
  * as follows:
  * <ol>
  * <li>
  * <code>digits=</code>, immediately followed by
  * the value of the digits setting as a numeric word.
  * <li>
  * <code>form=</code>, immediately followed by
  * the value of the form setting as an uppercase word
  * (one of <code>SCIENTIFIC</code>, <code>PLAIN</code>, or
  * <code>ENGINEERING</code>).
  * <li>
  * <code>lostDigits=</code>, immediately followed by
  * the value of the lostDigits setting
  * (<code>1</code> if enabled, <code>0</code> if disabled).
  * <li>
  * <code>roundingMode=</code>, immediately followed by
  * the value of the roundingMode setting as a word.
  * This word will be the same as the name of the corresponding public
  * constant.
  * </ol>
  * <p>
  * For example:
  * <br><code>
  * digits=9 form=SCIENTIFIC lostDigits=0 roundingMode=ROUND_HALF_UP
  * </code>
  * <p>
  * Additional words may be appended to the result of
  * <code>toString</code> in the future if more properties are added
  * to the class.
  *
  * @return a <code>String</code> representing the context settings.
  * @stable ICU 2.0
  */
 
 //--public java.lang.String toString(){
 function toString() {
  //--java.lang.String formstr=null;
  var formstr=null;
  //--int r=0;
  var r=0;
  //--java.lang.String roundword=null;
  var roundword=null;
  {/*select*/
  if (this.form==this.SCIENTIFIC)
   formstr="SCIENTIFIC";
  else if (this.form==this.ENGINEERING)
   formstr="ENGINEERING";
  else{
   formstr="PLAIN";/* form=PLAIN */
  }
  }
  {var $1=this.ROUNDS.length;r=0;r:for(;$1>0;$1--,r++){
   if (this.roundingMode==this.ROUNDS[r]) 
    {
     roundword=this.ROUNDWORDS[r];
     break r;
    }
   }
  }/*r*/
  return "digits="+this.digits+" "+"form="+formstr+" "+"lostDigits="+(this.lostDigits?"1":"0")+" "+"roundingMode="+roundword;
  }

 
 /* <sgml> Test whether round is valid. </sgml> */
 // This could be made shared for use by BigDecimal for setScale.
 
 //--private static boolean isValidRound(int testround){
 function isValidRound(testround) {
  //--int r=0;
  var r=0;
  {var $2=this.ROUNDS.length;r=0;r:for(;$2>0;$2--,r++){
   if (testround==this.ROUNDS[r]) 
    return true;
   }
  }/*r*/
  return false;
  }


/* Generated from 'BigDecimal.nrx' 8 Sep 2000 11:10:50 [v2.00] */
/* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
//--package com.ibm.icu.math;
//--import java.math.BigInteger;
//--import com.ibm.icu.impl.Utility;

/* ------------------------------------------------------------------ */
/* BigDecimal -- Decimal arithmetic for Java                          */
/* ------------------------------------------------------------------ */
/* Copyright IBM Corporation, 1996, 2000.  All Rights Reserved.       */
/*                                                                    */
/* The BigDecimal class provides immutable arbitrary-precision        */
/* floating point (including integer) decimal numbers.                */
/*                                                                    */
/* As the numbers are decimal, there is an exact correspondence       */
/* between an instance of a BigDecimal object and its String          */
/* representation; the BigDecimal class provides direct conversions   */
/* to and from String and character array objects, and well as        */
/* conversions to and from the Java primitive types (which may not    */
/* be exact).                                                         */
/* ------------------------------------------------------------------ */
/* Notes:                                                             */
/*                                                                    */
/* 1. A BigDecimal object is never changed in value once constructed; */
/*    this avoids the need for locking.  Note in particular that the  */
/*    mantissa array may be shared between many BigDecimal objects,   */
/*    so that once exposed it must not be altered.                    */
/*                                                                    */
/* 2. This class looks at MathContext class fields directly (for      */
/*    performance).  It must not and does not change them.            */
/*                                                                    */
/* 3. Exponent checking is delayed until finish(), as we know         */
/*    intermediate calculations cannot cause 31-bit overflow.         */
/*    [This assertion depends on MAX_DIGITS in MathContext.]          */
/*                                                                    */
/* 4. Comments for the public API now follow the javadoc conventions. */
/*    The NetRexx -comments option is used to pass these comments     */
/*    through to the generated Java code (with -format, if desired).  */
/*                                                                    */
/* 5. System.arraycopy is faster than explicit loop as follows        */
/*      Mean length 4:  equal                                         */
/*      Mean length 8:  x2                                            */
/*      Mean length 16: x3                                            */
/*      Mean length 24: x4                                            */
/*    From prior experience, we expect mean length a little below 8,  */
/*    but arraycopy is still the one to use, in general, until later  */
/*    measurements suggest otherwise.                                 */
/*                                                                    */
/* 6. 'DMSRCN' referred to below is the original (1981) IBM S/370     */
/*    assembler code implementation of the algorithms below; it is    */
/*    now called IXXRCN and is available with the OS/390 and VM/ESA   */
/*    operating systems.                                              */
/* ------------------------------------------------------------------ */
/* Change History:                                                    */
/* 1997.09.02 Initial version (derived from netrexx.lang classes)     */
/* 1997.09.12 Add lostDigits checking                                 */
/* 1997.10.06 Change mantissa to a byte array                         */
/* 1997.11.22 Rework power [did not prepare arguments, etc.]          */
/* 1997.12.13 multiply did not prepare arguments                      */
/* 1997.12.14 add did not prepare and align arguments correctly       */
/* 1998.05.02 0.07 packaging changes suggested by Sun and Oracle      */
/* 1998.05.21 adjust remainder operator finalization                  */
/* 1998.06.04 rework to pass MathContext to finish() and round()      */
/* 1998.06.06 change format to use round(); support rounding modes    */
/* 1998.06.25 rename to BigDecimal and begin merge                    */
/*            zero can now have trailing zeros (i.e., exp\=0)         */
/* 1998.06.28 new methods: movePointXxxx, scale, toBigInteger         */
/*                         unscaledValue, valueof                     */
/* 1998.07.01 improve byteaddsub to allow array reuse, etc.           */
/* 1998.07.01 make null testing explicit to avoid JIT bug [Win32]     */
/* 1998.07.07 scaled division  [divide(BigDecimal, int, int)]         */
/* 1998.07.08 setScale, faster equals                                 */
/* 1998.07.11 allow 1E6 (no sign) <sigh>; new double/float conversion */
/* 1998.10.12 change package to com.ibm.icu.math                          */
/* 1998.12.14 power operator no longer rounds RHS [to match ANSI]     */
/*            add toBigDecimal() and BigDecimal(java.math.BigDecimal) */
/* 1998.12.29 improve byteaddsub by using table lookup                */
/* 1999.02.04 lostdigits=0 behaviour rounds instead of digits+1 guard */
/* 1999.02.05 cleaner code for BigDecimal(char[])                     */
/* 1999.02.06 add javadoc comments                                    */
/* 1999.02.11 format() changed from 7 to 2 method form                */
/* 1999.03.05 null pointer checking is no longer explicit             */
/* 1999.03.05 simplify; changes from discussion with J. Bloch:        */
/*            null no longer permitted for MathContext; drop boolean, */
/*            byte, char, float, short constructor, deprecate double  */
/*            constructor, no blanks in string constructor, add       */
/*            offset and length version of char[] constructor;        */
/*            add valueOf(double); drop booleanValue, charValue;      */
/*            add ...Exact versions of remaining convertors           */
/* 1999.03.13 add toBigIntegerExact                                   */
/* 1999.03.13 1.00 release to IBM Centre for Java Technology          */
/* 1999.05.27 1.01 correct 0-0.2 bug under scaled arithmetic          */
/* 1999.06.29 1.02 constructors should not allow exponent > 9 digits  */
/* 1999.07.03 1.03 lost digits should not be checked if digits=0      */
/* 1999.07.06      lost digits Exception message changed              */
/* 1999.07.10 1.04 more work on 0-0.2 (scaled arithmetic)             */
/* 1999.07.17      improve messages from pow method                   */
/* 1999.08.08      performance tweaks                                 */
/* 1999.08.15      fastpath in multiply                               */
/* 1999.11.05 1.05 fix problem in intValueExact [e.g., 5555555555]    */
/* 1999.12.22 1.06 remove multiply fastpath, and improve performance  */
/* 2000.01.01      copyright update [Y2K has arrived]                 */
/* 2000.06.18 1.08 no longer deprecate BigDecimal(double)             */
/* ------------------------------------------------------------------ */


/* JavaScript conversion (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany */



function div(a, b) {
    return (a-(a%b))/b;
}

BigDecimal.prototype.div = div;

function arraycopy(src, srcindex, dest, destindex, length) {
    var i;
    if (destindex > srcindex) {
        // in case src and dest are equals, but also doesn't hurt
        // if they are different
        for (i = length-1; i >= 0; --i) {
            dest[i+destindex] = src[i+srcindex];
        }
    } else {
        for (i = 0; i < length; ++i) {
            dest[i+destindex] = src[i+srcindex];
        }
    }
}

BigDecimal.prototype.arraycopy = arraycopy;

function createArrayWithZeros(length) {
    var retVal = new Array(length);
    var i;
    for (i = 0; i < length; ++i) {
        retVal[i] = 0;
    }
    return retVal;
}

BigDecimal.prototype.createArrayWithZeros = createArrayWithZeros;


/**
 * The <code>BigDecimal</code> class implements immutable
 * arbitrary-precision decimal numbers.  The methods of the
 * <code>BigDecimal</code> class provide operations for fixed and
 * floating point arithmetic, comparison, format conversions, and
 * hashing.
 * <p>
 * As the numbers are decimal, there is an exact correspondence between
 * an instance of a <code>BigDecimal</code> object and its
 * <code>String</code> representation; the <code>BigDecimal</code> class
 * provides direct conversions to and from <code>String</code> and
 * character array (<code>char[]</code>) objects, as well as conversions
 * to and from the Java primitive types (which may not be exact) and
 * <code>BigInteger</code>.
 * <p>
 * In the descriptions of constructors and methods in this documentation,
 * the value of a <code>BigDecimal</code> number object is shown as the
 * result of invoking the <code>toString()</code> method on the object.
 * The internal representation of a decimal number is neither defined
 * nor exposed, and is not permitted to affect the result of any
 * operation.
 * <p>
 * The floating point arithmetic provided by this class is defined by
 * the ANSI X3.274-1996 standard, and is also documented at
 * <code>http://www2.hursley.ibm.com/decimal</code>
 * <br><i>[This URL will change.]</i>
 *
 * <h3>Operator methods</h3>
 * <p>
 * Operations on <code>BigDecimal</code> numbers are controlled by a
 * {@link MathContext} object, which provides the context (precision and
 * other information) for the operation. Methods that can take a
 * <code>MathContext</code> parameter implement the standard arithmetic
 * operators for <code>BigDecimal</code> objects and are known as
 * <i>operator methods</i>.  The default settings provided by the
 * constant {@link MathContext#DEFAULT} (<code>digits=9,
 * form=SCIENTIFIC, lostDigits=false, roundingMode=ROUND_HALF_UP</code>)
 * perform general-purpose floating point arithmetic to nine digits of
 * precision.  The <code>MathContext</code> parameter must not be
 * <code>null</code>.
 * <p>
 * Each operator method also has a version provided which does
 * not take a <code>MathContext</code> parameter.  For this version of
 * each method, the context settings used are <code>digits=0,
 * form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP</code>;
 * these settings perform fixed point arithmetic with unlimited
 * precision, as defined for the original BigDecimal class in Java 1.1
 * and Java 1.2.
 * <p>
 * For monadic operators, only the optional <code>MathContext</code>
 * parameter is present; the operation acts upon the current object.
 * <p>
 * For dyadic operators, a <code>BigDecimal</code> parameter is always
 * present; it must not be <code>null</code>.
 * The operation acts with the current object being the left-hand operand
 * and the <code>BigDecimal</code> parameter being the right-hand operand.
 * <p>
 * For example, adding two <code>BigDecimal</code> objects referred to
 * by the names <code>award</code> and <code>extra</code> could be
 * written as any of:
 * <p><code>
 *     award.add(extra)
 * <br>award.add(extra, MathContext.DEFAULT)
 * <br>award.add(extra, acontext)
 * </code>
 * <p>
 * (where <code>acontext</code> is a <code>MathContext</code> object),
 * which would return a <code>BigDecimal</code> object whose value is
 * the result of adding <code>award</code> and <code>extra</code> under
 * the appropriate context settings.
 * <p>
 * When a <code>BigDecimal</code> operator method is used, a set of
 * rules define what the result will be (and, by implication, how the
 * result would be represented as a character string).
 * These rules are defined in the BigDecimal arithmetic documentation
 * (see the URL above), but in summary:
 * <ul>
 * <li>Results are normally calculated with up to some maximum number of
 * significant digits.
 * For example, if the <code>MathContext</code> parameter for an operation
 * were <code>MathContext.DEFAULT</code> then the result would be
 * rounded to 9 digits; the division of 2 by 3 would then result in
 * 0.666666667.
 * <br>
 * You can change the default of 9 significant digits by providing the
 * method with a suitable <code>MathContext</code> object. This lets you
 * calculate using as many digits as you need -- thousands, if necessary.
 * Fixed point (scaled) arithmetic is indicated by using a
 * <code>digits</code> setting of 0 (or omitting the
 * <code>MathContext</code> parameter).
 * <br>
 * Similarly, you can change the algorithm used for rounding from the
 * default "classic" algorithm.
 * <li>
 * In standard arithmetic (that is, when the <code>form</code> setting
 * is not <code>PLAIN</code>), a zero result is always expressed as the
 * single digit <code>'0'</code> (that is, with no sign, decimal point,
 * or exponent part).
 * <li>
 * Except for the division and power operators in standard arithmetic,
 * trailing zeros are preserved (this is in contrast to binary floating
 * point operations and most electronic calculators, which lose the
 * information about trailing zeros in the fractional part of results).
 * <br>
 * So, for example:
 * <p><code>
 *     new BigDecimal("2.40").add(     new BigDecimal("2"))      =&gt; "4.40"
 * <br>new BigDecimal("2.40").subtract(new BigDecimal("2"))      =&gt; "0.40"
 * <br>new BigDecimal("2.40").multiply(new BigDecimal("2"))      =&gt; "4.80"
 * <br>new BigDecimal("2.40").divide(  new BigDecimal("2"), def) =&gt; "1.2"
 * </code>
 * <p>where the value on the right of the <code>=&gt;</code> would be the
 * result of the operation, expressed as a <code>String</code>, and
 * <code>def</code> (in this and following examples) refers to
 * <code>MathContext.DEFAULT</code>).
 * This preservation of trailing zeros is desirable for most
 * calculations (including financial calculations).
 * If necessary, trailing zeros may be easily removed using division by 1.
 * <li>
 * In standard arithmetic, exponential form is used for a result
 * depending on its value and the current setting of <code>digits</code>
 * (the default is 9 digits).
 * If the number of places needed before the decimal point exceeds the
 * <code>digits</code> setting, or the absolute value of the number is
 * less than <code>0.000001</code>, then the number will be expressed in
 * exponential notation; thus
 * <p><code>
 *   new BigDecimal("1e+6").multiply(new BigDecimal("1e+6"), def)
 * </code>
 * <p>results in <code>1E+12</code> instead of
 * <code>1000000000000</code>, and
 * <p><code>
 *   new BigDecimal("1").divide(new BigDecimal("3E+10"), def)
 * </code>
 * <p>results in <code>3.33333333E-11</code> instead of
 * <code>0.0000000000333333333</code>.
 * <p>
 * The form of the exponential notation (scientific or engineering) is
 * determined by the <code>form</code> setting.
 * <eul>
 * <p>
 * The names of methods in this class follow the conventions established
 * by <code>java.lang.Number</code>, <code>java.math.BigInteger</code>,
 * and <code>java.math.BigDecimal</code> in Java 1.1 and Java 1.2.
 *
 * @see     MathContext
 * @author  Mike Cowlishaw
 * @stable ICU 2.0
 */

//--public class BigDecimal extends java.lang.Number implements java.io.Serializable,java.lang.Comparable{
//-- private static final java.lang.String $0="BigDecimal.nrx";

 //-- methods
 BigDecimal.prototype.abs = abs;
 BigDecimal.prototype.add = add;
 BigDecimal.prototype.compareTo = compareTo;
 BigDecimal.prototype.divide = divide;
 BigDecimal.prototype.divideInteger = divideInteger;
 BigDecimal.prototype.max = max;
 BigDecimal.prototype.min = min;
 BigDecimal.prototype.multiply = multiply;
 BigDecimal.prototype.negate = negate;
 BigDecimal.prototype.plus = plus;
 BigDecimal.prototype.pow = pow;
 BigDecimal.prototype.remainder = remainder;
 BigDecimal.prototype.subtract = subtract;
 BigDecimal.prototype.equals = equals;
 BigDecimal.prototype.format = format;
 BigDecimal.prototype.intValueExact = intValueExact;
 BigDecimal.prototype.movePointLeft = movePointLeft;
 BigDecimal.prototype.movePointRight = movePointRight;
 BigDecimal.prototype.scale = scale;
 BigDecimal.prototype.setScale = setScale;
 BigDecimal.prototype.signum = signum;
 BigDecimal.prototype.toString = toString;
 BigDecimal.prototype.layout = layout;
 BigDecimal.prototype.intcheck = intcheck;
 BigDecimal.prototype.dodivide = dodivide;
 BigDecimal.prototype.bad = bad;
 BigDecimal.prototype.badarg = badarg;
 BigDecimal.prototype.extend = extend;
 BigDecimal.prototype.byteaddsub = byteaddsub;
 BigDecimal.prototype.diginit = diginit;
 BigDecimal.prototype.clone = clone;
 BigDecimal.prototype.checkdigits = checkdigits;
 BigDecimal.prototype.round = round;
 BigDecimal.prototype.allzero = allzero;
 BigDecimal.prototype.finish = finish;


 /* ----- Constants ----- */
 /* properties constant public */ // useful to others
 // the rounding modes (copied here for upwards compatibility)
 /**
  * Rounding mode to round to a more positive number.
  * @see MathContext#ROUND_CEILING
  * @stable ICU 2.0
  */
 //--public static final int ROUND_CEILING=com.ibm.icu.math.MathContext.ROUND_CEILING;
 BigDecimal.prototype.ROUND_CEILING = MathContext.prototype.ROUND_CEILING;
 
 /**
  * Rounding mode to round towards zero.
  * @see MathContext#ROUND_DOWN
  * @stable ICU 2.0
  */
 //--public static final int ROUND_DOWN=com.ibm.icu.math.MathContext.ROUND_DOWN;
 BigDecimal.prototype.ROUND_DOWN = MathContext.prototype.ROUND_DOWN;
 
 /**
  * Rounding mode to round to a more negative number.
  * @see MathContext#ROUND_FLOOR
  * @stable ICU 2.0
  */
 //--public static final int ROUND_FLOOR=com.ibm.icu.math.MathContext.ROUND_FLOOR;
 BigDecimal.prototype.ROUND_FLOOR = MathContext.prototype.ROUND_FLOOR;
 
 /**
  * Rounding mode to round to nearest neighbor, where an equidistant
  * value is rounded down.
  * @see MathContext#ROUND_HALF_DOWN
  * @stable ICU 2.0
  */
 //--public static final int ROUND_HALF_DOWN=com.ibm.icu.math.MathContext.ROUND_HALF_DOWN;
 BigDecimal.prototype.ROUND_HALF_DOWN = MathContext.prototype.ROUND_HALF_DOWN;
 
 /**
  * Rounding mode to round to nearest neighbor, where an equidistant
  * value is rounded to the nearest even neighbor.
  * @see MathContext#ROUND_HALF_EVEN
  * @stable ICU 2.0
  */
 //--public static final int ROUND_HALF_EVEN=com.ibm.icu.math.MathContext.ROUND_HALF_EVEN;
 BigDecimal.prototype.ROUND_HALF_EVEN = MathContext.prototype.ROUND_HALF_EVEN;
 
 /**
  * Rounding mode to round to nearest neighbor, where an equidistant
  * value is rounded up.
  * @see MathContext#ROUND_HALF_UP
  * @stable ICU 2.0
  */
 //--public static final int ROUND_HALF_UP=com.ibm.icu.math.MathContext.ROUND_HALF_UP;
 BigDecimal.prototype.ROUND_HALF_UP = MathContext.prototype.ROUND_HALF_UP;
 
 /**
  * Rounding mode to assert that no rounding is necessary.
  * @see MathContext#ROUND_UNNECESSARY
  * @stable ICU 2.0
  */
 //--public static final int ROUND_UNNECESSARY=com.ibm.icu.math.MathContext.ROUND_UNNECESSARY;
 BigDecimal.prototype.ROUND_UNNECESSARY = MathContext.prototype.ROUND_UNNECESSARY;
 
 /**
  * Rounding mode to round away from zero.
  * @see MathContext#ROUND_UP
  * @stable ICU 2.0
  */
 //--public static final int ROUND_UP=com.ibm.icu.math.MathContext.ROUND_UP;
 BigDecimal.prototype.ROUND_UP = MathContext.prototype.ROUND_UP;
 
 /* properties constant private */ // locals
 //--private static final byte ispos=1; // ind: indicates positive (must be 1)
 //--private static final byte iszero=0; // ind: indicates zero     (must be 0)
 //--private static final byte isneg=-1; // ind: indicates negative (must be -1)
 BigDecimal.prototype.ispos = 1;
 BigDecimal.prototype.iszero = 0;
 BigDecimal.prototype.isneg = -1;
 // [later could add NaN, +/- infinity, here]
 
 //--private static final int MinExp=-999999999; // minimum exponent allowed
 //--private static final int MaxExp=999999999; // maximum exponent allowed
 //--private static final int MinArg=-999999999; // minimum argument integer
 //--private static final int MaxArg=999999999; // maximum argument integer
 BigDecimal.prototype.MinExp=-999999999; // minimum exponent allowed
 BigDecimal.prototype.MaxExp=999999999; // maximum exponent allowed
 BigDecimal.prototype.MinArg=-999999999; // minimum argument integer
 BigDecimal.prototype.MaxArg=999999999; // maximum argument integer
 
 //--private static final com.ibm.icu.math.MathContext plainMC=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN); // context for plain unlimited math
 BigDecimal.prototype.plainMC=new MathContext(0, MathContext.prototype.PLAIN);

 /* properties constant private unused */ // present but not referenced
 
 // Serialization version
 //--private static final long serialVersionUID=8245355804974198832L;
 
 //--private static final java.lang.String copyright=" Copyright (c) IBM Corporation 1996, 2000.  All rights reserved. ";
 
 /* properties static private */
 // Precalculated constant arrays (used by byteaddsub)
 //--private static byte bytecar[]=new byte[(90+99)+1]; // carry/borrow array
 //--private static byte bytedig[]=diginit(); // next digit array
 BigDecimal.prototype.bytecar = new Array((90+99)+1);
 BigDecimal.prototype.bytedig = diginit();
 
 /**
  * The <code>BigDecimal</code> constant "0".
  *
  * @see #ONE
  * @see #TEN
  * @stable ICU 2.0
  */
 //--public static final com.ibm.icu.math.BigDecimal ZERO=new com.ibm.icu.math.BigDecimal((long)0); // use long as we want the int constructor
 // .. to be able to use this, for speed
BigDecimal.prototype.ZERO = new BigDecimal("0");

 /**
  * The <code>BigDecimal</code> constant "1".
  *
  * @see #TEN
  * @see #ZERO
  * @stable ICU 2.0
  */
 //--public static final com.ibm.icu.math.BigDecimal ONE=new com.ibm.icu.math.BigDecimal((long)1); // use long as we want the int constructor
 // .. to be able to use this, for speed
BigDecimal.prototype.ONE = new BigDecimal("1");

 /**
  * The <code>BigDecimal</code> constant "10".
  *
  * @see #ONE
  * @see #ZERO
  * @stable ICU 2.0
  */
 //--public static final com.ibm.icu.math.BigDecimal TEN=new com.ibm.icu.math.BigDecimal(10);
 BigDecimal.prototype.TEN = new BigDecimal("10");
 
 /* ----- Instance properties [all private and immutable] ----- */
 /* properties private */
 
 /**
  * The indicator. This may take the values:
  * <ul>
  * <li>ispos  -- the number is positive
  * <li>iszero -- the number is zero
  * <li>isneg  -- the number is negative
  * </ul>
  *
  * @serial
  */
 //--private byte ind; // assumed undefined
 // Note: some code below assumes IND = Sign [-1, 0, 1], at present.
 // We only need two bits for this, but use a byte [also permits
 // smooth future extension].
 
 /**
  * The formatting style. This may take the values:
  * <ul>
  * <li>MathContext.PLAIN        -- no exponent needed
  * <li>MathContext.SCIENTIFIC   -- scientific notation required
  * <li>MathContext.ENGINEERING  -- engineering notation required
  * </ul>
  * <p>
  * This property is an optimization; it allows us to defer number
  * layout until it is actually needed as a string, hence avoiding
  * unnecessary formatting.
  *
  * @serial
  */
 //--private byte form=(byte)com.ibm.icu.math.MathContext.PLAIN; // assumed PLAIN
 // We only need two bits for this, at present, but use a byte
 // [again, to allow for smooth future extension]
 
 /**
  * The value of the mantissa.
  * <p>
  * Once constructed, this may become shared between several BigDecimal
  * objects, so must not be altered.
  * <p>
  * For efficiency (speed), this is a byte array, with each byte
  * taking a value of 0 -> 9.
  * <p>
  * If the first byte is 0 then the value of the number is zero (and
  * mant.length=1, except when constructed from a plain number, for
  * example, 0.000).
  *
  * @serial
  */
 //--private byte mant[]; // assumed null
 
 /**
  * The exponent.
  * <p>
  * For fixed point arithmetic, scale is <code>-exp</code>, and can
  * apply to zero.
  *
  * Note that this property can have a value less than MinExp when
  * the mantissa has more than one digit.
  *
  * @serial
  */
 //--private int exp;
 // assumed 0
 
 /* ---------------------------------------------------------------- */
 /* Constructors                                                     */
 /* ---------------------------------------------------------------- */
 
 /**
  * Constructs a <code>BigDecimal</code> object from a
  * <code>java.math.BigDecimal</code>.
  * <p>
  * Constructs a <code>BigDecimal</code> as though the parameter had
  * been represented as a <code>String</code> (using its
  * <code>toString</code> method) and the
  * {@link #BigDecimal(java.lang.String)} constructor had then been
  * used.
  * The parameter must not be <code>null</code>.
  * <p>
  * <i>(Note: this constructor is provided only in the
  * <code>com.ibm.icu.math</code> version of the BigDecimal class.
  * It would not be present in a <code>java.math</code> version.)</i>
  *
  * @param bd The <code>BigDecimal</code> to be translated.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(java.math.BigDecimal bd){
 //-- this(bd.toString());
 //-- return;}

 /**
  * Constructs a <code>BigDecimal</code> object from a
  * <code>BigInteger</code>, with scale 0.
  * <p>
  * Constructs a <code>BigDecimal</code> which is the exact decimal
  * representation of the <code>BigInteger</code>, with a scale of
  * zero.
  * The value of the <code>BigDecimal</code> is identical to the value
  * of the <code>BigInteger</code>.
  * The parameter must not be <code>null</code>.
  * <p>
  * The <code>BigDecimal</code> will contain only decimal digits,
  * prefixed with a leading minus sign (hyphen) if the
  * <code>BigInteger</code> is negative.  A leading zero will be
  * present only if the <code>BigInteger</code> is zero.
  *
  * @param bi The <code>BigInteger</code> to be converted.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(java.math.BigInteger bi){
 //-- this(bi.toString(10));
 //-- return;}
 // exp remains 0
 
 /**
  * Constructs a <code>BigDecimal</code> object from a
  * <code>BigInteger</code> and a scale.
  * <p>
  * Constructs a <code>BigDecimal</code> which is the exact decimal
  * representation of the <code>BigInteger</code>, scaled by the
  * second parameter, which may not be negative.
  * The value of the <code>BigDecimal</code> is the
  * <code>BigInteger</code> divided by ten to the power of the scale.
  * The <code>BigInteger</code> parameter must not be
  * <code>null</code>.
  * <p>
  * The <code>BigDecimal</code> will contain only decimal digits, (with
  * an embedded decimal point followed by <code>scale</code> decimal
  * digits if the scale is positive), prefixed with a leading minus
  * sign (hyphen) if the <code>BigInteger</code> is negative.  A
  * leading zero will be present only if the <code>BigInteger</code> is
  * zero.
  *
  * @param  bi    The <code>BigInteger</code> to be converted.
  * @param  scale The <code>int</code> specifying the scale.
  * @throws NumberFormatException if the scale is negative.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(java.math.BigInteger bi,int scale){
 //-- this(bi.toString(10));
 //-- if (scale<0) 
 //--  throw new java.lang.NumberFormatException("Negative scale:"+" "+scale);
 //-- exp=(int)-scale; // exponent is -scale
 //-- return;}

 /**
  * Constructs a <code>BigDecimal</code> object from an array of characters.
  * <p>
  * Constructs a <code>BigDecimal</code> as though a
  * <code>String</code> had been constructed from the character array
  * and the {@link #BigDecimal(java.lang.String)} constructor had then
  * been used. The parameter must not be <code>null</code>.
  * <p>
  * Using this constructor is faster than using the
  * <code>BigDecimal(String)</code> constructor if the string is
  * already available in character array form.
  *
  * @param inchars The <code>char[]</code> array containing the number
  *                to be converted.
  * @throws NumberFormatException if the parameter is not a valid
  *                number.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(char inchars[]){
 //-- this(inchars,0,inchars.length);
 //-- return;}

 /**
  * Constructs a <code>BigDecimal</code> object from an array of characters.
  * <p>
  * Constructs a <code>BigDecimal</code> as though a
  * <code>String</code> had been constructed from the character array
  * (or a subarray of that array) and the
  * {@link #BigDecimal(java.lang.String)} constructor had then been
  * used. The first parameter must not be <code>null</code>, and the
  * subarray must be wholly contained within it.
  * <p>
  * Using this constructor is faster than using the
  * <code>BigDecimal(String)</code> constructor if the string is
  * already available within a character array.
  *
  * @param inchars The <code>char[]</code> array containing the number
  *                to be converted.
  * @param offset  The <code>int</code> offset into the array of the
  *                start of the number to be converted.
  * @param length  The <code>int</code> length of the number.
  * @throws NumberFormatException if the parameter is not a valid
  *                number for any reason.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(char inchars[],int offset,int length){super();
 function BigDecimal() {
  //-- members
  this.ind = 0;
  this.form = MathContext.prototype.PLAIN;
  this.mant = null;
  this.exp = 0;

  //-- overloaded ctor
  if (BigDecimal.arguments.length == 0)
   return;
  var inchars;
  var offset;
  var length;
  if (BigDecimal.arguments.length == 1)
   {
    inchars = BigDecimal.arguments[0];
    offset = 0;
    length = inchars.length;
   }
  else
   {
    inchars = BigDecimal.arguments[0];
    offset = BigDecimal.arguments[1];
    length = BigDecimal.arguments[2];
   }
  if (typeof inchars == "string")
   {
    inchars = inchars.split("");
   }

  //--boolean exotic;
  var exotic;
  //--boolean hadexp;
  var hadexp;
  //--int d;
  var d;
  //--int dotoff;
  var dotoff;
  //--int last;
  var last;
  //--int i=0;
  var i=0;
  //--char si=0;
  var si=0;
  //--boolean eneg=false;
  var eneg=false;
  //--int k=0;
  var k=0;
  //--int elen=0;
  var elen=0;
  //--int j=0;
  var j=0;
  //--char sj=0;
  var sj=0;
  //--int dvalue=0;
  var dvalue=0;
  //--int mag=0;
  var mag=0;
  // This is the primary constructor; all incoming strings end up
  // here; it uses explicit (inline) parsing for speed and to avoid
  // generating intermediate (temporary) objects of any kind.
  // 1998.06.25: exponent form built only if E/e in string
  // 1998.06.25: trailing zeros not removed for zero
  // 1999.03.06: no embedded blanks; allow offset and length
  if (length<=0) 
   this.bad("BigDecimal(): ", inchars); // bad conversion (empty string)
  // [bad offset will raise array bounds exception]
  
  /* Handle and step past sign */
  this.ind=this.ispos; // assume positive
  if (inchars[0]==('-')) 
   {
    length--;
    if (length==0) 
     this.bad("BigDecimal(): ", inchars); // nothing after sign
    this.ind=this.isneg;
    offset++;
   }
  else 
   if (inchars[0]==('+')) 
    {
     length--;
     if (length==0) 
      this.bad("BigDecimal(): ", inchars); // nothing after sign
     offset++;
    }
  
  /* We're at the start of the number */
  exotic=false; // have extra digits
  hadexp=false; // had explicit exponent
  d=0; // count of digits found
  dotoff=-1; // offset where dot was found
  last=-1; // last character of mantissa
  {var $1=length;i=offset;i:for(;$1>0;$1--,i++){
   si=inchars[i];
   if (si>='0')  // test for Arabic digit
    if (si<='9') 
     {
      last=i;
      d++; // still in mantissa
      continue i;
     }
   if (si=='.') 
    { // record and ignore
     if (dotoff>=0) 
      this.bad("BigDecimal(): ", inchars); // two dots
     dotoff=i-offset; // offset into mantissa
     continue i;
    }
   if (si!='e') 
    if (si!='E') 
     { // expect an extra digit
      if (si<'0' || si>'9') 
       this.bad("BigDecimal(): ", inchars); // not a number
      // defer the base 10 check until later to avoid extra method call
      exotic=true; // will need conversion later
      last=i;
      d++; // still in mantissa
      continue i;
     }
   /* Found 'e' or 'E' -- now process explicit exponent */
   // 1998.07.11: sign no longer required
   if ((i-offset)>(length-2)) 
    this.bad("BigDecimal(): ", inchars); // no room for even one digit
   eneg=false;
   if ((inchars[i+1])==('-')) 
    {
     eneg=true;
     k=i+2;
    }
   else 
    if ((inchars[i+1])==('+')) 
     k=i+2;
    else 
     k=i+1;
   // k is offset of first expected digit
   elen=length-((k-offset)); // possible number of digits
   if ((elen==0)||(elen>9)) 
    this.bad("BigDecimal(): ", inchars); // 0 or more than 9 digits
   {var $2=elen;j=k;j:for(;$2>0;$2--,j++){
    sj=inchars[j];
    if (sj<'0') 
     this.bad("BigDecimal(): ", inchars); // always bad
    if (sj>'9') 
     { // maybe an exotic digit
      /*if (si<'0' || si>'9') 
       this.bad(inchars); // not a number
      dvalue=java.lang.Character.digit(sj,10); // check base
      if (dvalue<0) 
       bad(inchars); // not base 10*/
      this.bad("BigDecimal(): ", inchars);
     }
    else 
     dvalue=sj-'0';
    this.exp=(this.exp*10)+dvalue;
    }
   }/*j*/
   if (eneg) 
    this.exp=-this.exp; // was negative
   hadexp=true; // remember we had one
   break i; // we are done
   }
  }/*i*/
  
  /* Here when all inspected */
  if (d==0) 
   this.bad("BigDecimal(): ", inchars); // no mantissa digits
  if (dotoff>=0) 
   this.exp=(this.exp+dotoff)-d; // adjust exponent if had dot
  
  /* strip leading zeros/dot (leave final if all 0's) */
  {var $3=last-1;i=offset;i:for(;i<=$3;i++){
   si=inchars[i];
   if (si=='0') 
    {
     offset++;
     dotoff--;
     d--;
    }
   else 
    if (si=='.') 
     {
      offset++; // step past dot
      dotoff--;
     }
    else 
     if (si<='9') 
      break i;/* non-0 */
     else 
      {/* exotic */
       //if ((java.lang.Character.digit(si,10))!=0) 
        break i; // non-0 or bad
       // is 0 .. strip like '0'
       //offset++;
       //dotoff--;
       //d--;
      }
   }
  }/*i*/
  
  /* Create the mantissa array */
  this.mant=new Array(d); // we know the length
  j=offset; // input offset
  if (exotic) 
   {exotica:do{ // slow: check for exotica
    {var $4=d;i=0;i:for(;$4>0;$4--,i++){
     if (i==dotoff) 
      j++; // at dot
     sj=inchars[j];
     if (sj<='9') 
      this.mant[i]=sj-'0';/* easy */
     else 
      {
       //dvalue=java.lang.Character.digit(sj,10);
       //if (dvalue<0) 
        this.bad("BigDecimal(): ", inchars); // not a number after all
       //mant[i]=(byte)dvalue;
      }
     j++;
     }
    }/*i*/
   }while(false);}/*exotica*/
  else 
   {simple:do{
    {var $5=d;i=0;i:for(;$5>0;$5--,i++){
     if (i==dotoff) 
      j++;
     this.mant[i]=inchars[j]-'0';
     j++;
     }
    }/*i*/
   }while(false);}/*simple*/
  
  /* Looks good.  Set the sign indicator and form, as needed. */
  // Trailing zeros are preserved
  // The rule here for form is:
  //   If no E-notation, then request plain notation
  //   Otherwise act as though add(0,DEFAULT) and request scientific notation
  // [form is already PLAIN]
  if (this.mant[0]==0) 
   {
    this.ind=this.iszero; // force to show zero
    // negative exponent is significant (e.g., -3 for 0.000) if plain
    if (this.exp>0) 
     this.exp=0; // positive exponent can be ignored
    if (hadexp) 
     { // zero becomes single digit from add
      this.mant=this.ZERO.mant;
      this.exp=0;
     }
   }
  else 
   { // non-zero
    // [ind was set earlier]
    // now determine form
    if (hadexp) 
     {
      this.form=MathContext.prototype.SCIENTIFIC;
      // 1999.06.29 check for overflow
      mag=(this.exp+this.mant.length)-1; // true exponent in scientific notation
      if ((mag<this.MinExp)||(mag>this.MaxExp)) 
       this.bad("BigDecimal(): ", inchars);
     }
   }
  // say 'BD(c[]): mant[0] mantlen exp ind form:' mant[0] mant.length exp ind form
  return;
  }

 /**
  * Constructs a <code>BigDecimal</code> object directly from a
  * <code>double</code>.
  * <p>
  * Constructs a <code>BigDecimal</code> which is the exact decimal
  * representation of the 64-bit signed binary floating point
  * parameter.
  * <p>
  * Note that this constructor it an exact conversion; it does not give
  * the same result as converting <code>num</code> to a
  * <code>String</code> using the <code>Double.toString()</code> method
  * and then using the {@link #BigDecimal(java.lang.String)}
  * constructor.
  * To get that result, use the static {@link #valueOf(double)}
  * method to construct a <code>BigDecimal</code> from a
  * <code>double</code>.
  *
  * @param num The <code>double</code> to be converted.
  * @throws NumberFormatException if the parameter is infinite or
  *            not a number.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(double num){
 //-- // 1999.03.06: use exactly the old algorithm
 //-- // 2000.01.01: note that this constructor does give an exact result,
 //-- //             so perhaps it should not be deprecated
 //-- // 2000.06.18: no longer deprecated
 //-- this((new java.math.BigDecimal(num)).toString());
 //-- return;}

 /**
  * Constructs a <code>BigDecimal</code> object directly from a
  * <code>int</code>.
  * <p>
  * Constructs a <code>BigDecimal</code> which is the exact decimal
  * representation of the 32-bit signed binary integer parameter.
  * The <code>BigDecimal</code> will contain only decimal digits,
  * prefixed with a leading minus sign (hyphen) if the parameter is
  * negative.
  * A leading zero will be present only if the parameter is zero.
  *
  * @param num The <code>int</code> to be converted.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(int num){super();
 //-- int mun;
 //-- int i=0;
 //-- // We fastpath commoners
 //-- if (num<=9) 
 //--  if (num>=(-9)) 
 //--   {singledigit:do{
 //--    // very common single digit case
 //--    {/*select*/
 //--    if (num==0)
 //--     {
 //--      mant=ZERO.mant;
 //--      ind=iszero;
 //--     }
 //--    else if (num==1)
 //--     {
 //--      mant=ONE.mant;
 //--      ind=ispos;
 //--     }
 //--    else if (num==(-1))
 //--     {
 //--      mant=ONE.mant;
 //--      ind=isneg;
 //--     }
 //--    else{
 //--     {
 //--      mant=new byte[1];
 //--      if (num>0) 
 //--       {
 //--        mant[0]=(byte)num;
 //--        ind=ispos;
 //--       }
 //--      else 
 //--       { // num<-1
 //--        mant[0]=(byte)((int)-num);
 //--        ind=isneg;
 //--       }
 //--     }
 //--    }
 //--    }
 //--    return;
 //--   }while(false);}/*singledigit*/
 //-- 
 //-- /* We work on negative numbers so we handle the most negative number */
 //-- if (num>0) 
 //--  {
 //--   ind=ispos;
 //--   num=(int)-num;
 //--  }
 //-- else 
 //--  ind=isneg;/* negative */ // [0 case already handled]
 //-- // [it is quicker, here, to pre-calculate the length with
 //-- // one loop, then allocate exactly the right length of byte array,
 //-- // then re-fill it with another loop]
 //-- mun=num; // working copy
 //-- {i=9;i:for(;;i--){
 //--  mun=mun/10;
 //--  if (mun==0) 
 //--   break i;
 //--  }
 //-- }/*i*/
 //-- // i is the position of the leftmost digit placed
 //-- mant=new byte[10-i];
 //-- {i=(10-i)-1;i:for(;;i--){
 //--  mant[i]=(byte)-(((byte)(num%10)));
 //--  num=num/10;
 //--  if (num==0) 
 //--   break i;
 //--  }
 //-- }/*i*/
 //-- return;
 //-- }

 /**
  * Constructs a <code>BigDecimal</code> object directly from a
  * <code>long</code>.
  * <p>
  * Constructs a <code>BigDecimal</code> which is the exact decimal
  * representation of the 64-bit signed binary integer parameter.
  * The <code>BigDecimal</code> will contain only decimal digits,
  * prefixed with a leading minus sign (hyphen) if the parameter is
  * negative.
  * A leading zero will be present only if the parameter is zero.
  *
  * @param num The <code>long</code> to be converted.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(long num){super();
 //-- long mun;
 //-- int i=0;
 //-- // Not really worth fastpathing commoners in this constructor [also,
 //-- // we use this to construct the static constants].
 //-- // This is much faster than: this(String.valueOf(num).toCharArray())
 //-- /* We work on negative num so we handle the most negative number */
 //-- if (num>0) 
 //--  {
 //--   ind=ispos;
 //--   num=(long)-num;
 //--  }
 //-- else 
 //--  if (num==0) 
 //--   ind=iszero;
 //--  else 
 //--   ind=isneg;/* negative */
 //-- mun=num;
 //-- {i=18;i:for(;;i--){
 //--  mun=mun/10;
 //--  if (mun==0) 
 //--   break i;
 //--  }
 //-- }/*i*/
 //-- // i is the position of the leftmost digit placed
 //-- mant=new byte[19-i];
 //-- {i=(19-i)-1;i:for(;;i--){
 //--  mant[i]=(byte)-(((byte)(num%10)));
 //--  num=num/10;
 //--  if (num==0) 
 //--   break i;
 //--  }
 //-- }/*i*/
 //-- return;
 //-- }

 /**
  * Constructs a <code>BigDecimal</code> object from a <code>String</code>.
  * <p>
  * Constructs a <code>BigDecimal</code> from the parameter, which must
  * not be <code>null</code> and must represent a valid <i>number</i>,
  * as described formally in the documentation referred to
  * {@link BigDecimal above}.
  * <p>
  * In summary, numbers in <code>String</code> form must have at least
  * one digit, may have a leading sign, may have a decimal point, and
  * exponential notation may be used.  They follow conventional syntax,
  * and may not contain blanks.
  * <p>
  * Some valid strings from which a <code>BigDecimal</code> might
  * be constructed are:
  * <pre>
  *       "0"         -- Zero
  *      "12"         -- A whole number
  *     "-76"         -- A signed whole number
  *      "12.70"      -- Some decimal places
  *     "+0.003"      -- Plus sign is allowed
  *      "17."        -- The same as 17
  *        ".5"       -- The same as 0.5
  *      "4E+9"       -- Exponential notation
  *       "0.73e-7"   -- Exponential notation
  * </pre>
  * <p>
  * (Exponential notation means that the number includes an optional
  * sign and a power of ten following an '</code>E</code>' that
  * indicates how the decimal point will be shifted.  Thus the
  * <code>"4E+9"</code> above is just a short way of writing
  * <code>4000000000</code>, and the <code>"0.73e-7"</code> is short
  * for <code>0.000000073</code>.)
  * <p>
  * The <code>BigDecimal</code> constructed from the String is in a
  * standard form, with no blanks, as though the
  * {@link #add(BigDecimal)} method had been used to add zero to the
  * number with unlimited precision.
  * If the string uses exponential notation (that is, includes an
  * <code>e</code> or an <code>E</code>), then the
  * <code>BigDecimal</code> number will be expressed in scientific
  * notation (where the power of ten is adjusted so there is a single
  * non-zero digit to the left of the decimal point); in this case if
  * the number is zero then it will be expressed as the single digit 0,
  * and if non-zero it will have an exponent unless that exponent would
  * be 0.  The exponent must fit in nine digits both before and after it
  * is expressed in scientific notation.
  * <p>
  * Any digits in the parameter must be decimal; that is,
  * <code>Character.digit(c, 10)</code> (where </code>c</code> is the
  * character in question) would not return -1.
  *
  * @param string The <code>String</code> to be converted.
  * @throws NumberFormatException if the parameter is not a valid
  * number.
  * @stable ICU 2.0
  */
 
 //--public BigDecimal(java.lang.String string){
 //-- this(string.toCharArray(),0,string.length());
 //-- return;}

 /* <sgml> Make a default BigDecimal object for local use. </sgml> */
 
 //--private BigDecimal(){super();
 //-- return;
 //-- }

 /* ---------------------------------------------------------------- */
 /* Operator methods [methods which take a context parameter]        */
 /* ---------------------------------------------------------------- */
 
 /**
  * Returns a plain <code>BigDecimal</code> whose value is the absolute
  * value of this <code>BigDecimal</code>.
  * <p>
  * The same as {@link #abs(MathContext)}, where the context is
  * <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will
  * be <code>this.scale()</code>
  *
  * @return A <code>BigDecimal</code> whose value is the absolute
  *         value of this <code>BigDecimal</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal abs(){
 //- return this.abs(plainMC);
 //- }

 /**
  * Returns a <code>BigDecimal</code> whose value is the absolute value
  * of this <code>BigDecimal</code>.
  * <p>
  * If the current object is zero or positive, then the same result as
  * invoking the {@link #plus(MathContext)} method with the same
  * parameter is returned.
  * Otherwise, the same result as invoking the
  * {@link #negate(MathContext)} method with the same parameter is
  * returned.
  *
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is the absolute
  *             value of this <code>BigDecimal</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal abs(com.ibm.icu.math.MathContext set){
 function abs() {
  var set;
  if (abs.arguments.length == 1)
   {
    set = abs.arguments[0];
   }
  else if (abs.arguments.length == 0)
   {
    set = this.plainMC;
   }
  else
   {
    throw "abs(): " + abs.arguments.length + " arguments given; expected 0 or 1"
   }
  if (this.ind==this.isneg) 
   return this.negate(set);
  return this.plus(set);
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this+rhs</code>, using fixed point arithmetic.
  * <p>
  * The same as {@link #add(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will be
  * the maximum of the scales of the two operands.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the addition.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this+rhs</code>, using fixed point arithmetic.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.add(rhs,plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is <code>this+rhs</code>.
  * <p>
  * Implements the addition (<b><code>+</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the addition.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this+rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function add() {
  var set;
  if (add.arguments.length == 2)
   {
    set = add.arguments[1];
   }
  else if (add.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "add(): " + add.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = add.arguments[0];
  //--com.ibm.icu.math.BigDecimal lhs;
  var lhs;
  //--int reqdig;
  var reqdig;
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  //--byte usel[];
  var usel;
  //--int usellen;
  var usellen;
  //--byte user[];
  var user;
  //--int userlen;
  var userlen;
  //--int newlen=0;
  var newlen=0;
  //--int tlen=0;
  var tlen=0;
  //--int mult=0;
  var mult=0;
  //--byte t[]=null;
  var t=null;
  //--int ia=0;
  var ia=0;
  //--int ib=0;
  var ib=0;
  //--int ea=0;
  var ea=0;
  //int eb=0;
  var eb=0;
  //byte ca=0;
  var ca=0;
  //--byte cb=0;
  var cb=0;
  /* determine requested digits and form */
  if (set.lostDigits) 
   this.checkdigits(rhs,set.digits);
  lhs=this; // name for clarity and proxy
  
  /* Quick exit for add floating 0 */
  // plus() will optimize to return same object if possible
  if (lhs.ind==0) 
   if (set.form!=MathContext.prototype.PLAIN) 
    return rhs.plus(set);
  if (rhs.ind==0) 
   if (set.form!=MathContext.prototype.PLAIN) 
    return lhs.plus(set);
  
  /* Prepare numbers (round, unless unlimited precision) */
  reqdig=set.digits; // local copy (heavily used)
  if (reqdig>0) 
   {
    if (lhs.mant.length>reqdig) 
     lhs=this.clone(lhs).round(set);
    if (rhs.mant.length>reqdig) 
     rhs=this.clone(rhs).round(set);
   // [we could reuse the new LHS for result in this case]
   }
  
  res=new BigDecimal(); // build result here
  
  /* Now see how much we have to pad or truncate lhs or rhs in order
     to align the numbers.  If one number is much larger than the
     other, then the smaller cannot affect the answer [but we may
     still need to pad with up to DIGITS trailing zeros]. */
  // Note sign may be 0 if digits (reqdig) is 0
  // usel and user will be the byte arrays passed to the adder; we'll
  // use them on all paths except quick exits
  usel=lhs.mant;
  usellen=lhs.mant.length;
  user=rhs.mant;
  userlen=rhs.mant.length;
  {padder:do{/*select*/
  if (lhs.exp==rhs.exp)
   {/* no padding needed */
    // This is the most common, and fastest, path
    res.exp=lhs.exp;
   }
  else if (lhs.exp>rhs.exp)
   { // need to pad lhs and/or truncate rhs
    newlen=(usellen+lhs.exp)-rhs.exp;
    /* If, after pad, lhs would be longer than rhs by digits+1 or
       more (and digits>0) then rhs cannot affect answer, so we only
       need to pad up to a length of DIGITS+1. */
    if (newlen>=((userlen+reqdig)+1)) 
     if (reqdig>0) 
      {
       // LHS is sufficient
       res.mant=usel;
       res.exp=lhs.exp;
       res.ind=lhs.ind;
       if (usellen<reqdig) 
        { // need 0 padding
         res.mant=this.extend(lhs.mant,reqdig);
         res.exp=res.exp-((reqdig-usellen));
        }
       return res.finish(set,false);
      }
    // RHS may affect result
    res.exp=rhs.exp; // expected final exponent
    if (newlen>(reqdig+1)) 
     if (reqdig>0) 
      {
       // LHS will be max; RHS truncated
       tlen=(newlen-reqdig)-1; // truncation length
       userlen=userlen-tlen;
       res.exp=res.exp+tlen;
       newlen=reqdig+1;
      }
    if (newlen>usellen) 
     usellen=newlen; // need to pad LHS
   }
  else{ // need to pad rhs and/or truncate lhs
   newlen=(userlen+rhs.exp)-lhs.exp;
   if (newlen>=((usellen+reqdig)+1)) 
    if (reqdig>0) 
     {
      // RHS is sufficient
      res.mant=user;
      res.exp=rhs.exp;
      res.ind=rhs.ind;
      if (userlen<reqdig) 
       { // need 0 padding
        res.mant=this.extend(rhs.mant,reqdig);
        res.exp=res.exp-((reqdig-userlen));
       }
      return res.finish(set,false);
     }
   // LHS may affect result
   res.exp=lhs.exp; // expected final exponent
   if (newlen>(reqdig+1)) 
    if (reqdig>0) 
     {
      // RHS will be max; LHS truncated
      tlen=(newlen-reqdig)-1; // truncation length
      usellen=usellen-tlen;
      res.exp=res.exp+tlen;
      newlen=reqdig+1;
     }
   if (newlen>userlen) 
    userlen=newlen; // need to pad RHS
  }
  }while(false);}/*padder*/
  
  /* OK, we have aligned mantissas.  Now add or subtract. */
  // 1998.06.27 Sign may now be 0 [e.g., 0.000] .. treat as positive
  // 1999.05.27 Allow for 00 on lhs [is not larger than 2 on rhs]
  // 1999.07.10 Allow for 00 on rhs [is not larger than 2 on rhs]
  if (lhs.ind==this.iszero) 
   res.ind=this.ispos;
  else 
   res.ind=lhs.ind; // likely sign, all paths
  if (((lhs.ind==this.isneg)?1:0)==((rhs.ind==this.isneg)?1:0))  // same sign, 0 non-negative
   mult=1;
  else 
   {signdiff:do{ // different signs, so subtraction is needed
    mult=-1; // will cause subtract
    /* Before we can subtract we must determine which is the larger,
       as our add/subtract routine only handles non-negative results
       so we may need to swap the operands. */
    {swaptest:do{/*select*/
    if (rhs.ind==this.iszero)
     ; // original A bigger
    else if ((usellen<userlen)||(lhs.ind==this.iszero))
     { // original B bigger
      t=usel;
      usel=user;
      user=t; // swap
      tlen=usellen;
      usellen=userlen;
      userlen=tlen; // ..
      res.ind=-res.ind; // and set sign
     }
    else if (usellen>userlen)
     ; // original A bigger
    else{
     {/* logical lengths the same */ // need compare
      /* may still need to swap: compare the strings */
      ia=0;
      ib=0;
      ea=usel.length-1;
      eb=user.length-1;
      {compare:for(;;){
       if (ia<=ea) 
        ca=usel[ia];
       else 
        {
         if (ib>eb) 
          {/* identical */
           if (set.form!=MathContext.prototype.PLAIN) 
            return this.ZERO;
           // [if PLAIN we must do the subtract, in case of 0.000 results]
           break compare;
          }
         ca=0;
        }
       if (ib<=eb) 
        cb=user[ib];
       else 
        cb=0;
       if (ca!=cb) 
        {
         if (ca<cb) 
          {/* swap needed */
           t=usel;
           usel=user;
           user=t; // swap
           tlen=usellen;
           usellen=userlen;
           userlen=tlen; // ..
           res.ind=-res.ind;
          }
         break compare;
        }
       /* mantissas the same, so far */
       ia++;
       ib++;
       }
      }/*compare*/
     } // lengths the same
    }
    }while(false);}/*swaptest*/
   }while(false);}/*signdiff*/
  
  /* here, A is > B if subtracting */
  // add [A+B*1] or subtract [A+(B*-1)]
  res.mant=this.byteaddsub(usel,usellen,user,userlen,mult,false);
  // [reuse possible only after chop; accounting makes not worthwhile]
  
  // Finish() rounds before stripping leading 0's, then sets form, etc.
  return res.finish(set,false);
  }

 /**
  * Compares this <code>BigDecimal</code> to another, using unlimited
  * precision.
  * <p>
  * The same as {@link #compareTo(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the comparison.
  * @return     An <code>int</code> whose value is -1, 0, or 1 as
  *             <code>this</code> is numerically less than, equal to,
  *             or greater than <code>rhs</code>.
  * @see    #compareTo(Object)
  * @stable ICU 2.0
  */
 
 //--public int compareTo(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.compareTo(rhs,plainMC);
 //-- }

 /**
  * Compares this <code>BigDecimal</code> to another.
  * <p>
  * Implements numeric comparison,
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns a result of type <code>int</code>.
  * <p>
  * The result will be:
  * <table cellpadding=2><tr>
  * <td align=right><b>-1</b></td>
  * <td>if the current object is less than the first parameter</td>
  * </tr><tr>
  * <td align=right><b>0</b></td>
  * <td>if the current object is equal to the first parameter</td>
  * </tr><tr>
  * <td align=right><b>1</b></td>
  * <td>if the current object is greater than the first parameter.</td>
  * </tr></table>
  * <p>
  * A {@link #compareTo(Object)} method is also provided.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the comparison.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     An <code>int</code> whose value is -1, 0, or 1 as
  *             <code>this</code> is numerically less than, equal to,
  *             or greater than <code>rhs</code>.
  * @see    #compareTo(Object)
  * @stable ICU 2.0
  */
 
 //public int compareTo(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function compareTo() {
  var set;
  if (compareTo.arguments.length == 2)
   {
    set = compareTo.arguments[1];
   }
  else if (compareTo.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "compareTo(): " + compareTo.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = compareTo.arguments[0];
  //--int thislength=0;
  var thislength=0;
  //--int i=0;
  var i=0;
  //--com.ibm.icu.math.BigDecimal newrhs;
  var newrhs;
  // rhs=null will raise NullPointerException, as per Comparable interface
  if (set.lostDigits) 
   this.checkdigits(rhs,set.digits);
  // [add will recheck in slowpath cases .. but would report -rhs]
  if ((this.ind==rhs.ind)&&(this.exp==rhs.exp)) 
   {
    /* sign & exponent the same [very common] */
    thislength=this.mant.length;
    if (thislength<rhs.mant.length) 
     return -this.ind;
    if (thislength>rhs.mant.length) 
     return this.ind;
    /* lengths are the same; we can do a straight mantissa compare
       unless maybe rounding [rounding is very unusual] */
    if ((thislength<=set.digits)||(set.digits==0)) 
     {
      {var $6=thislength;i=0;i:for(;$6>0;$6--,i++){
       if (this.mant[i]<rhs.mant[i]) 
        return -this.ind;
       if (this.mant[i]>rhs.mant[i]) 
        return this.ind;
       }
      }/*i*/
      return 0; // identical
     }
   /* drop through for full comparison */
   }
  else 
   {
    /* More fastpaths possible */
    if (this.ind<rhs.ind) 
     return -1;
    if (this.ind>rhs.ind) 
     return 1;
   }
  /* carry out a subtract to make the comparison */
  newrhs=this.clone(rhs); // safe copy
  newrhs.ind=-newrhs.ind; // prepare to subtract
  return this.add(newrhs,set).ind; // add, and return sign of result
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this/rhs</code>, using fixed point arithmetic.
  * <p>
  * The same as {@link #divide(BigDecimal, int)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the rounding mode is {@link MathContext#ROUND_HALF_UP}.
  *
  * The length of the decimal part (the scale) of the result will be
  * the same as the scale of the current object, if the latter were
  * formatted without exponential notation.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the division.
  * @return     A plain <code>BigDecimal</code> whose value is
  *             <code>this/rhs</code>, using fixed point arithmetic.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.dodivide('D',rhs,plainMC,-1);
 //-- }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this/rhs</code>, using fixed point arithmetic and a
  * rounding mode.
  * <p>
  * The same as {@link #divide(BigDecimal, int, int)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the second parameter is <code>this.scale()</code>, and
  * the third is <code>round</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will
  * therefore be the same as the scale of the current object, if the
  * latter were formatted without exponential notation.
  * <p>
  * @param  rhs   The <code>BigDecimal</code> for the right hand side of
  *               the division.
  * @param  round The <code>int</code> rounding mode to be used for
  *               the division (see the {@link MathContext} class).
  * @return       A plain <code>BigDecimal</code> whose value is
  *               <code>this/rhs</code>, using fixed point arithmetic
  *               and the specified rounding mode.
  * @throws IllegalArgumentException if <code>round</code> is not a
  *               valid rounding mode.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @throws ArithmeticException if <code>round</code> is {@link
  *               MathContext#ROUND_UNNECESSARY} and
  *               <code>this.scale()</code> is insufficient to
  *               represent the result exactly.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int round){
 //-- com.ibm.icu.math.MathContext set;
 //-- set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round, too]
 //-- return this.dodivide('D',rhs,set,-1); // take scale from LHS
 //-- }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this/rhs</code>, using fixed point arithmetic and a
  * given scale and rounding mode.
  * <p>
  * The same as {@link #divide(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * <code>new MathContext(0, MathContext.PLAIN, false, round)</code>,
  * except that the length of the decimal part (the scale) to be used
  * for the result is explicit rather than being taken from
  * <code>this</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will be
  * the same as the scale of the current object, if the latter were
  * formatted without exponential notation.
  * <p>
  * @param  rhs   The <code>BigDecimal</code> for the right hand side of
  *               the division.
  * @param  scale The <code>int</code> scale to be used for the result.
  * @param  round The <code>int</code> rounding mode to be used for
  *               the division (see the {@link MathContext} class).
  * @return       A plain <code>BigDecimal</code> whose value is
  *               <code>this/rhs</code>, using fixed point arithmetic
  *               and the specified rounding mode.
  * @throws IllegalArgumentException if <code>round</code> is not a
  *               valid rounding mode.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @throws ArithmeticException if <code>scale</code> is negative.
  * @throws ArithmeticException if <code>round</code> is {@link
  *               MathContext#ROUND_UNNECESSARY} and <code>scale</code>
  *               is insufficient to represent the result exactly.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int scale,int round){
 //-- com.ibm.icu.math.MathContext set;
 //-- if (scale<0) 
 //--  throw new java.lang.ArithmeticException("Negative scale:"+" "+scale);
 //-- set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round]
 //-- return this.dodivide('D',rhs,set,scale);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is <code>this/rhs</code>.
  * <p>
  * Implements the division (<b><code>/</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the division.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this/rhs</code>.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function divide() {
  var set;
  var scale = -1;
  if (divide.arguments.length == 2)
   {
    if (typeof divide.arguments[1] == 'number')
     {
      set=new MathContext(0,MathContext.prototype.PLAIN,false,divide.arguments[1]); // [checks round, too]
     }
    else
     {
      set = divide.arguments[1];
     }
   }
  else if (divide.arguments.length == 3)
   {
    scale = divide.arguments[1];
    if (scale<0) 
     throw "divide(): Negative scale: "+scale;
    set=new MathContext(0,MathContext.prototype.PLAIN,false,divide.arguments[2]); // [checks round]
   }
  else if (divide.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "divide(): " + divide.arguments.length + " arguments given; expected between 1 and 3"
   }
  var rhs = divide.arguments[0];
  return this.dodivide('D',rhs,set,scale);
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is the integer
  * part of <code>this/rhs</code>.
  * <p>
  * The same as {@link #divideInteger(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the integer division.
  * @return     A <code>BigDecimal</code> whose value is the integer
  *             part of <code>this/rhs</code>.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs){
 //-- // scale 0 to drop .000 when plain
 //-- return this.dodivide('I',rhs,plainMC,0);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is the integer
  * part of <code>this/rhs</code>.
  * <p>
  * Implements the integer division operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the integer division.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is the integer
  *             part of <code>this/rhs</code>.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @throws ArithmeticException if the result will not fit in the
  *             number of digits specified for the context.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function divideInteger() {
  var set;
  if (divideInteger.arguments.length == 2)
   {
    set = divideInteger.arguments[1];
   }
  else if (divideInteger.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "divideInteger(): " + divideInteger.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = divideInteger.arguments[0];
  // scale 0 to drop .000 when plain
  return this.dodivide('I',rhs,set,0);
  }
 
 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * the maximum of <code>this</code> and <code>rhs</code>.
  * <p>
  * The same as {@link #max(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the comparison.
  * @return     A <code>BigDecimal</code> whose value is
  *             the maximum of <code>this</code> and <code>rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.max(rhs,plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is
  * the maximum of <code>this</code> and <code>rhs</code>.
  * <p>
  * Returns the larger of the current object and the first parameter.
  * <p>
  * If calling the {@link #compareTo(BigDecimal, MathContext)} method
  * with the same parameters would return <code>1</code> or
  * <code>0</code>, then the result of calling the
  * {@link #plus(MathContext)} method on the current object (using the
  * same <code>MathContext</code> parameter) is returned.
  * Otherwise, the result of calling the {@link #plus(MathContext)}
  * method on the first parameter object (using the same
  * <code>MathContext</code> parameter) is returned.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the comparison.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             the maximum of <code>this</code> and <code>rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function max() {
  var set;
  if (max.arguments.length == 2)
   {
    set = max.arguments[1];
   }
  else if (max.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "max(): " + max.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = max.arguments[0];
  if ((this.compareTo(rhs,set))>=0) 
   return this.plus(set);
  else 
   return rhs.plus(set);
  }
 
 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * the minimum of <code>this</code> and <code>rhs</code>.
  * <p>
  * The same as {@link #min(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the comparison.
  * @return     A <code>BigDecimal</code> whose value is
  *             the minimum of <code>this</code> and <code>rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.min(rhs,plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is
  * the minimum of <code>this</code> and <code>rhs</code>.
  * <p>
  * Returns the smaller of the current object and the first parameter.
  * <p>
  * If calling the {@link #compareTo(BigDecimal, MathContext)} method
  * with the same parameters would return <code>-1</code> or
  * <code>0</code>, then the result of calling the
  * {@link #plus(MathContext)} method on the current object (using the
  * same <code>MathContext</code> parameter) is returned.
  * Otherwise, the result of calling the {@link #plus(MathContext)}
  * method on the first parameter object (using the same
  * <code>MathContext</code> parameter) is returned.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the comparison.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             the minimum of <code>this</code> and <code>rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function min() {
  var set;
  if (min.arguments.length == 2)
   {
    set = min.arguments[1];
   }
  else if (min.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "min(): " + min.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = min.arguments[0];
  if ((this.compareTo(rhs,set))<=0) 
   return this.plus(set);
  else 
   return rhs.plus(set);
  }
 
 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this*rhs</code>, using fixed point arithmetic.
  * <p>
  * The same as {@link #add(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will be
  * the sum of the scales of the operands, if they were formatted
  * without exponential notation.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the multiplication.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this*rhs</code>, using fixed point arithmetic.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.multiply(rhs,plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is <code>this*rhs</code>.
  * <p>
  * Implements the multiplication (<b><code>*</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the multiplication.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this*rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function multiply() {
  var set;
  if (multiply.arguments.length == 2)
   {
    set = multiply.arguments[1];
   }
  else if (multiply.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "multiply(): " + multiply.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = multiply.arguments[0];
  //--com.ibm.icu.math.BigDecimal lhs;
  var lhs;
  //--int padding;
  var padding;
  //--int reqdig;
  var reqdig;
  //--byte multer[]=null;
  var multer=null;
  //--byte multand[]=null;
  var multand=null;
  //--int multandlen;
  var multandlen;
  //--int acclen=0;
  var acclen=0;
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  //--byte acc[];
  var acc;
  //--int n=0;
  var n=0;
  //--byte mult=0;
  var mult=0;
  if (set.lostDigits) 
   this.checkdigits(rhs,set.digits);
  lhs=this; // name for clarity and proxy
  
  /* Prepare numbers (truncate, unless unlimited precision) */
  padding=0; // trailing 0's to add
  reqdig=set.digits; // local copy
  if (reqdig>0) 
   {
    if (lhs.mant.length>reqdig) 
     lhs=this.clone(lhs).round(set);
    if (rhs.mant.length>reqdig) 
     rhs=this.clone(rhs).round(set);
   // [we could reuse the new LHS for result in this case]
   }
  else 
   {/* unlimited */
    // fixed point arithmetic will want every trailing 0; we add these
    // after the calculation rather than before, for speed.
    if (lhs.exp>0) 
     padding=padding+lhs.exp;
    if (rhs.exp>0) 
     padding=padding+rhs.exp;
   }
  
  // For best speed, as in DMSRCN, we use the shorter number as the
  // multiplier and the longer as the multiplicand.
  // 1999.12.22: We used to special case when the result would fit in
  //             a long, but with Java 1.3 this gave no advantage.
  if (lhs.mant.length<rhs.mant.length) 
   {
    multer=lhs.mant;
    multand=rhs.mant;
   }
  else 
   {
    multer=rhs.mant;
    multand=lhs.mant;
   }
  
  /* Calculate how long result byte array will be */
  multandlen=(multer.length+multand.length)-1; // effective length
  // optimize for 75% of the cases where a carry is expected...
  if ((multer[0]*multand[0])>9) 
   acclen=multandlen+1;
  else 
   acclen=multandlen;
  
  /* Now the main long multiplication loop */
  res=new BigDecimal(); // where we'll build result
  acc=this.createArrayWithZeros(acclen); // accumulator, all zeros
  // 1998.07.01: calculate from left to right so that accumulator goes
  // to likely final length on first addition; this avoids a one-digit
  // extension (and object allocation) each time around the loop.
  // Initial number therefore has virtual zeros added to right.
  {var $7=multer.length;n=0;n:for(;$7>0;$7--,n++){
   mult=multer[n];
   if (mult!=0) 
    { // [optimization]
     // accumulate [accumulator is reusable array]
     acc=this.byteaddsub(acc,acc.length,multand,multandlen,mult,true);
    }
   // divide multiplicand by 10 for next digit to right
   multandlen--; // 'virtual length'
   }
  }/*n*/
  
  res.ind=lhs.ind*rhs.ind; // final sign
  res.exp=(lhs.exp+rhs.exp)-padding; // final exponent
  // [overflow is checked by finish]
  
  /* add trailing zeros to the result, if necessary */
  if (padding==0) 
   res.mant=acc;
  else 
   res.mant=this.extend(acc,acc.length+padding); // add trailing 0s
  return res.finish(set,false);
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>-this</code>.
  * <p>
  * The same as {@link #negate(MathContext)}, where the context is
  * <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will be
  * be <code>this.scale()</code>
  *
  *
  * @return A <code>BigDecimal</code> whose value is
  *         <code>-this</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal negate(){
 //-- return this.negate(plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is <code>-this</code>.
  * <p>
  * Implements the negation (Prefix <b><code>-</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  *
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return A <code>BigDecimal</code> whose value is
  *         <code>-this</code>.
  * @stable ICU 2.0
  */
 
 //public com.ibm.icu.math.BigDecimal negate(com.ibm.icu.math.MathContext set){
 function negate() {
  var set;
  if (negate.arguments.length == 1)
   {
    set = negate.arguments[0];
   }
  else if (negate.arguments.length == 0)
   {
    set = this.plainMC;
   }
  else
   {
    throw "negate(): " + negate.arguments.length + " arguments given; expected 0 or 1"
   }
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  // Originally called minus(), changed to matched Java precedents
  // This simply clones, flips the sign, and possibly rounds
  if (set.lostDigits) 
   this.checkdigits(null,set.digits);
  res=this.clone(this); // safe copy
  res.ind=-res.ind;
  return res.finish(set,false);
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>+this</code>.
  * Note that <code>this</code> is not necessarily a
  * plain <code>BigDecimal</code>, but the result will always be.
  * <p>
  * The same as {@link #plus(MathContext)}, where the context is
  * <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will be
  * be <code>this.scale()</code>
  *
  * @return A <code>BigDecimal</code> whose value is
  *         <code>+this</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal plus(){
 //-- return this.plus(plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is
  * <code>+this</code>.
  * <p>
  * Implements the plus (Prefix <b><code>+</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  * <p>
  * This method is useful for rounding or otherwise applying a context
  * to a decimal value.
  *
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return A <code>BigDecimal</code> whose value is
  *         <code>+this</code>.
  * @stable ICU 2.0
  */
 
 //public com.ibm.icu.math.BigDecimal plus(com.ibm.icu.math.MathContext set){
 function plus() {
  var set;
  if (plus.arguments.length == 1)
   {
    set = plus.arguments[0];
   }
  else if (plus.arguments.length == 0)
   {
    set = this.plainMC;
   }
  else
   {
    throw "plus(): " + plus.arguments.length + " arguments given; expected 0 or 1"
   }
  // This clones and forces the result to the new settings
  // May return same object
  if (set.lostDigits) 
   this.checkdigits(null,set.digits);
  // Optimization: returns same object for some common cases
  if (set.form==MathContext.prototype.PLAIN) 
   if (this.form==MathContext.prototype.PLAIN) 
    {
     if (this.mant.length<=set.digits) 
      return this;
     if (set.digits==0) 
      return this;
    }
  return this.clone(this).finish(set,false);
  }
 
 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this**rhs</code>, using fixed point arithmetic.
  * <p>
  * The same as {@link #pow(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The parameter is the power to which the <code>this</code> will be
  * raised; it must be in the range 0 through 999999999, and must
  * have a decimal part of zero.  Note that these restrictions may be
  * removed in the future, so they should not be used as a test for a
  * whole number.
  * <p>
  * In addition, the power must not be negative, as no
  * <code>MathContext</code> is used and so the result would then
  * always be 0.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the operation (the power).
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this**rhs</code>, using fixed point arithmetic.
  * @throws ArithmeticException if <code>rhs</code> is out of range or
  *             is not a whole number.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.pow(rhs,plainMC);
 //-- }
 // The name for this method is inherited from the precedent set by the
 // BigInteger and Math classes.
 
 /**
  * Returns a <code>BigDecimal</code> whose value is <code>this**rhs</code>.
  * <p>
  * Implements the power (<b><code>**</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  * <p>
  * The first parameter is the power to which the <code>this</code>
  * will be raised; it must be in the range -999999999 through
  * 999999999, and must have a decimal part of zero.  Note that these
  * restrictions may be removed in the future, so they should not be
  * used as a test for a whole number.
  * <p>
  * If the <code>digits</code> setting of the <code>MathContext</code>
  * parameter is 0, the power must be zero or positive.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the operation (the power).
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this**rhs</code>.
  * @throws ArithmeticException if <code>rhs</code> is out of range or
  *             is not a whole number.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function pow() {
  var set;
  if (pow.arguments.length == 2)
   {
    set = pow.arguments[1];
   }
  else if (pow.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "pow(): " + pow.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = pow.arguments[0];
  //--int n;
  var n;
  //--com.ibm.icu.math.BigDecimal lhs;
  var lhs;
  //--int reqdig;
  var reqdig;
  //-- int workdigits=0;
  var workdigits=0;
  //--int L=0;
  var L=0;
  //--com.ibm.icu.math.MathContext workset;
  var workset;
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  //--boolean seenbit;
  var seenbit;
  //--int i=0;
  var i=0;
  if (set.lostDigits) 
   this.checkdigits(rhs,set.digits);
  n=rhs.intcheck(this.MinArg,this.MaxArg); // check RHS by the rules
  lhs=this; // clarified name
  
  reqdig=set.digits; // local copy (heavily used)
  if (reqdig==0) 
   {
    if (rhs.ind==this.isneg) 
     //--throw new java.lang.ArithmeticException("Negative power:"+" "+rhs.toString());
     throw "pow(): Negative power: " + rhs.toString()
    workdigits=0;
   }
  else 
   {/* non-0 digits */
    if ((rhs.mant.length+rhs.exp)>reqdig) 
     //--throw new java.lang.ArithmeticException("Too many digits:"+" "+rhs.toString());
     throw "pow(): Too many digits: " + rhs.toString()
    
    /* Round the lhs to DIGITS if need be */
    if (lhs.mant.length>reqdig) 
     lhs=this.clone(lhs).round(set);
    
    /* L for precision calculation [see ANSI X3.274-1996] */
    L=rhs.mant.length+rhs.exp; // length without decimal zeros/exp
    workdigits=(reqdig+L)+1; // calculate the working DIGITS
   }
  
  /* Create a copy of set for working settings */
  // Note: no need to check for lostDigits again.
  // 1999.07.17 Note: this construction must follow RHS check
  workset=new MathContext(workdigits,set.form,false,set.roundingMode);
  
  res=this.ONE; // accumulator
  if (n==0) 
   return res; // x**0 == 1
  if (n<0) 
   n=-n; // [rhs.ind records the sign]
  seenbit=false; // set once we've seen a 1-bit
  {i=1;i:for(;;i++){ // for each bit [top bit ignored]
   n=n+n; // shift left 1 bit
   if (n<0) 
    { // top bit is set
     seenbit=true; // OK, we're off
     res=res.multiply(lhs,workset); // acc=acc*x
    }
   if (i==31) 
    break i; // that was the last bit
   if ((!seenbit)) 
    continue i; // we don't have to square 1
   res=res.multiply(res,workset); // acc=acc*acc [square]
   }
  }/*i*/ // 32 bits
  if (rhs.ind<0)  // was a **-n [hence digits>0]
   res=this.ONE.divide(res,workset); // .. so acc=1/acc
  return res.finish(set,true); // round and strip [original digits]
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * the remainder of <code>this/rhs</code>, using fixed point arithmetic.
  * <p>
  * The same as {@link #remainder(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * This is not the modulo operator -- the result may be negative.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the remainder operation.
  * @return     A <code>BigDecimal</code> whose value is the remainder
  *             of <code>this/rhs</code>, using fixed point arithmetic.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.dodivide('R',rhs,plainMC,-1);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is the remainder of
  * <code>this/rhs</code>.
  * <p>
  * Implements the remainder operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  * <p>
  * This is not the modulo operator -- the result may be negative.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the remainder operation.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is the remainder
  *             of <code>this+rhs</code>.
  * @throws ArithmeticException if <code>rhs</code> is zero.
  * @throws ArithmeticException if the integer part of the result will
  *             not fit in the number of digits specified for the
  *             context.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function remainder() {
  var set;
  if (remainder.arguments.length == 2)
   {
    set = remainder.arguments[1];
   }
  else if (remainder.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "remainder(): " + remainder.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = remainder.arguments[0];
  return this.dodivide('R',rhs,set,-1);
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose value is
  * <code>this-rhs</code>, using fixed point arithmetic.
  * <p>
  * The same as {@link #subtract(BigDecimal, MathContext)},
  * where the <code>BigDecimal</code> is <code>rhs</code>,
  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
  * <p>
  * The length of the decimal part (the scale) of the result will be
  * the maximum of the scales of the two operands.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the subtraction.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this-rhs</code>, using fixed point arithmetic.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs){
 //-- return this.subtract(rhs,plainMC);
 //-- }

 /**
  * Returns a <code>BigDecimal</code> whose value is <code>this-rhs</code>.
  * <p>
  * Implements the subtraction (<b><code>-</code></b>) operator
  * (as defined in the decimal documentation, see {@link BigDecimal
  * class header}),
  * and returns the result as a <code>BigDecimal</code> object.
  *
  * @param  rhs The <code>BigDecimal</code> for the right hand side of
  *             the subtraction.
  * @param  set The <code>MathContext</code> arithmetic settings.
  * @return     A <code>BigDecimal</code> whose value is
  *             <code>this-rhs</code>.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
 function subtract() {
  var set;
  if (subtract.arguments.length == 2)
   {
    set = subtract.arguments[1];
   }
  else if (subtract.arguments.length == 1)
   {
    set = this.plainMC;
   }
  else
   {
    throw "subtract(): " + subtract.arguments.length + " arguments given; expected 1 or 2"
   }
  var rhs = subtract.arguments[0];
  //--com.ibm.icu.math.BigDecimal newrhs;
  var newrhs;
  if (set.lostDigits) 
   this.checkdigits(rhs,set.digits);
  // [add will recheck .. but would report -rhs]
  /* carry out the subtraction */
  // we could fastpath -0, but it is too rare.
  newrhs=this.clone(rhs); // safe copy
  newrhs.ind=-newrhs.ind; // prepare to subtract
  return this.add(newrhs,set); // arithmetic
  }

 /* ---------------------------------------------------------------- */
 /* Other methods                                                    */
 /* ---------------------------------------------------------------- */
 
 /**
  * Converts this <code>BigDecimal</code> to a <code>byte</code>.
  * If the <code>BigDecimal</code> has a non-zero decimal part or is
  * out of the possible range for a <code>byte</code> (8-bit signed
  * integer) result then an <code>ArithmeticException</code> is thrown.
  *
  * @return A <code>byte</code> equal in value to <code>this</code>.
  * @throws ArithmeticException if <code>this</code> has a non-zero
  *                 decimal part, or will not fit in a <code>byte</code>.
  * @stable ICU 2.0
  */
 
 //--public byte byteValueExact(){
 //-- int num;
 //-- num=this.intValueExact(); // will check decimal part too
 //-- if ((num>127)|(num<(-128))) 
 //--  throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
 //-- return (byte)num;
 //-- }

 /**
  * Compares this <code>BigDecimal</code> with the value of the parameter.
  * <p>
  * If the parameter is <code>null</code>, or is not an instance of the
  * <code>BigDecimal</code> type, an exception is thrown.
  * Otherwise, the parameter is cast to type <code>BigDecimal</code>
  * and the result of the {@link #compareTo(BigDecimal)} method,
  * using the cast parameter, is returned.
  * <p>
  * The {@link #compareTo(BigDecimal, MathContext)} method should be
  * used when a <code>MathContext</code> is needed for the comparison.
  *
  * @param  rhs The <code>Object</code> for the right hand side of
  *             the comparison.
  * @return     An <code>int</code> whose value is -1, 0, or 1 as
  *             <code>this</code> is numerically less than, equal to,
  *             or greater than <code>rhs</code>.
  * @throws ClassCastException if <code>rhs</code> cannot be cast to
  *                 a <code>BigDecimal</code> object.
  * @see    #compareTo(BigDecimal)
  * @stable ICU 2.0
  */
 
 //--public int compareTo(java.lang.Object rhsobj){
 //-- // the cast in the next line will raise ClassCastException if necessary
 //-- return compareTo((com.ibm.icu.math.BigDecimal)rhsobj,plainMC);
 //-- }

 /**
  * Converts this <code>BigDecimal</code> to a <code>double</code>.
  * If the <code>BigDecimal</code> is out of the possible range for a
  * <code>double</code> (64-bit signed floating point) result then an
  * <code>ArithmeticException</code> is thrown.
  * <p>
  * The double produced is identical to result of expressing the
  * <code>BigDecimal</code> as a <code>String</code> and then
  * converting it using the <code>Double(String)</code> constructor;
  * this can result in values of <code>Double.NEGATIVE_INFINITY</code>
  * or <code>Double.POSITIVE_INFINITY</code>.
  *
  * @return A <code>double</code> corresponding to <code>this</code>.
  * @stable ICU 2.0
  */
 
 //--public double doubleValue(){
 //-- // We go via a String [as does BigDecimal in JDK 1.2]
 //-- // Next line could possibly raise NumberFormatException
 //-- return java.lang.Double.valueOf(this.toString()).doubleValue();
 //-- }

 /**
  * Compares this <code>BigDecimal</code> with <code>rhs</code> for
  * equality.
  * <p>
  * If the parameter is <code>null</code>, or is not an instance of the
  * BigDecimal type, or is not exactly equal to the current
  * <code>BigDecimal</code> object, then <i>false</i> is returned.
  * Otherwise, <i>true</i> is returned.
  * <p>
  * "Exactly equal", here, means that the <code>String</code>
  * representations of the <code>BigDecimal</code> numbers are
  * identical (they have the same characters in the same sequence).
  * <p>
  * The {@link #compareTo(BigDecimal, MathContext)} method should be
  * used for more general comparisons.
  * @param  rhs The <code>Object</code> for the right hand side of
  *             the comparison.
  * @return     A <code>boolean</code> whose value <i>true</i> if and
  *             only if the operands have identical string representations.
  * @throws ClassCastException if <code>rhs</code> cannot be cast to
  *                 a <code>BigDecimal</code> object.
  * @stable ICU 2.0
  * @see    #compareTo(Object)
  * @see    #compareTo(BigDecimal)
  * @see    #compareTo(BigDecimal, MathContext)
  */
 
 //--public boolean equals(java.lang.Object obj){
 function equals(obj) {
  //--com.ibm.icu.math.BigDecimal rhs;
  var rhs;
  //--int i=0;
  var i=0;
  //--char lca[]=null;
  var lca=null;
  //--char rca[]=null;
  var rca=null;
  // We are equal iff toString of both are exactly the same
  if (obj==null) 
   return false; // not equal
  if ((!(((obj instanceof BigDecimal))))) 
   return false; // not a decimal
  rhs=obj; // cast; we know it will work
  if (this.ind!=rhs.ind) 
   return false; // different signs never match
  if (((this.mant.length==rhs.mant.length)&&(this.exp==rhs.exp))&&(this.form==rhs.form)) 
   
   { // mantissas say all
    // here with equal-length byte arrays to compare
    {var $8=this.mant.length;i=0;i:for(;$8>0;$8--,i++){
     if (this.mant[i]!=rhs.mant[i]) 
      return false;
     }
    }/*i*/
   }
  else 
   { // need proper layout
    lca=this.layout(); // layout to character array
    rca=rhs.layout();
    if (lca.length!=rca.length) 
     return false; // mismatch
    // here with equal-length character arrays to compare
    {var $9=lca.length;i=0;i:for(;$9>0;$9--,i++){
     if (lca[i]!=rca[i]) 
      return false;
     }
    }/*i*/
   }
  return true; // arrays have identical content
  }

 /**
  * Converts this <code>BigDecimal</code> to a <code>float</code>.
  * If the <code>BigDecimal</code> is out of the possible range for a
  * <code>float</code> (32-bit signed floating point) result then an
  * <code>ArithmeticException</code> is thrown.
  * <p>
  * The float produced is identical to result of expressing the
  * <code>BigDecimal</code> as a <code>String</code> and then
  * converting it using the <code>Float(String)</code> constructor;
  * this can result in values of <code>Float.NEGATIVE_INFINITY</code>
  * or <code>Float.POSITIVE_INFINITY</code>.
  *
  * @return A <code>float</code> corresponding to <code>this</code>.
  * @stable ICU 2.0
  */
 
 //--public float floatValue(){
 //-- return java.lang.Float.valueOf(this.toString()).floatValue();
 //-- }

 /**
  * Returns the <code>String</code> representation of this
  * <code>BigDecimal</code>, modified by layout parameters.
  * <p>
  * <i>This method is provided as a primitive for use by more
  * sophisticated classes, such as <code>DecimalFormat</code>, that
  * can apply locale-sensitive editing of the result.  The level of
  * formatting that it provides is a necessary part of the BigDecimal
  * class as it is sensitive to and must follow the calculation and
  * rounding rules for BigDecimal arithmetic.
  * However, if the function is provided elsewhere, it may be removed
  * from this class. </i>
  * <p>
  * The parameters, for both forms of the <code>format</code> method
  * are all of type <code>int</code>.
  * A value of -1 for any parameter indicates that the default action
  * or value for that parameter should be used.
  * <p>
  * The parameters, <code>before</code> and <code>after</code>,
  * specify the number of characters to be used for the integer part
  * and decimal part of the result respectively.  Exponential notation
  * is not used. If either parameter is -1 (which indicates the default
  * action), the number of characters used will be exactly as many as
  * are needed for that part.
  * <p>
  * <code>before</code> must be a positive number; if it is larger than
  * is needed to contain the integer part, that part is padded on the
  * left with blanks to the requested length. If <code>before</code> is
  * not large enough to contain the integer part of the number
  * (including the sign, for negative numbers) an exception is thrown.
  * <p>
  * <code>after</code> must be a non-negative number; if it is not the
  * same size as the decimal part of the number, the number will be
  * rounded (or extended with zeros) to fit.  Specifying 0 for
  * <code>after</code> will cause the number to be rounded to an
  * integer (that is, it will have no decimal part or decimal point).
  * The rounding method will be the default,
  * <code>MathContext.ROUND_HALF_UP</code>.
  * <p>
  * Other rounding methods, and the use of exponential notation, can
  * be selected by using {@link #format(int,int,int,int,int,int)}.
  * Using the two-parameter form of the method has exactly the same
  * effect as using the six-parameter form with the final four
  * parameters all being -1.
  *
  * @param  before The <code>int</code> specifying the number of places
  *                before the decimal point.  Use -1 for 'as many as
  *                are needed'.
  * @param  after  The <code>int</code> specifying the number of places
  *                after the decimal point.  Use -1 for 'as many as are
  *                needed'.
  * @return        A <code>String</code> representing this
  *                <code>BigDecimal</code>, laid out according to the
  *                specified parameters
  * @throws ArithmeticException if the number cannot be laid out as
  *                requested.
  * @throws IllegalArgumentException if a parameter is out of range.
  * @stable ICU 2.0
  * @see    #toString
  * @see    #toCharArray
  */
 
 //--public java.lang.String format(int before,int after){
 //-- return format(before,after,-1,-1,com.ibm.icu.math.MathContext.SCIENTIFIC,ROUND_HALF_UP);
 //-- }

 /**
  * Returns the <code>String</code> representation of this
  * <code>BigDecimal</code>, modified by layout parameters and allowing
  * exponential notation.
  * <p>
  * <i>This method is provided as a primitive for use by more
  * sophisticated classes, such as <code>DecimalFormat</code>, that
  * can apply locale-sensitive editing of the result.  The level of
  * formatting that it provides is a necessary part of the BigDecimal
  * class as it is sensitive to and must follow the calculation and
  * rounding rules for BigDecimal arithmetic.
  * However, if the function is provided elsewhere, it may be removed
  * from this class. </i>
  * <p>
  * The parameters are all of type <code>int</code>.
  * A value of -1 for any parameter indicates that the default action
  * or value for that parameter should be used.
  * <p>
  * The first two parameters (<code>before</code> and
  * <code>after</code>) specify the number of characters to be used for
  * the integer part and decimal part of the result respectively, as
  * defined for {@link #format(int,int)}.
  * If either of these is -1 (which indicates the default action), the
  * number of characters used will be exactly as many as are needed for
  * that part.
  * <p>
  * The remaining parameters control the use of exponential notation
  * and rounding.  Three (<code>explaces</code>, <code>exdigits</code>,
  * and <code>exform</code>) control the exponent part of the result.
  * As before, the default action for any of these parameters may be
  * selected by using the value -1.
  * <p>
  * <code>explaces</code> must be a positive number; it sets the number
  * of places (digits after the sign of the exponent) to be used for
  * any exponent part, the default (when <code>explaces</code> is -1)
  * being to use as many as are needed.
  * If <code>explaces</code> is not -1, space is always reserved for
  * an exponent; if one is not needed (for example, if the exponent
  * will be 0) then <code>explaces</code>+2 blanks are appended to the
  * result.
  * <!-- (This preserves vertical alignment of similarly formatted
  *       numbers in a monospace font.) -->
  * If <code>explaces</code> is not -1 and is not large enough to
  * contain the exponent, an exception is thrown.
  * <p>
  * <code>exdigits</code> sets the trigger point for use of exponential
  * notation. If, before any rounding, the number of places needed
  * before the decimal point exceeds <code>exdigits</code>, or if the
  * absolute value of the result is less than <code>0.000001</code>,
  * then exponential form will be used, provided that
  * <code>exdigits</code> was specified.
  * When <code>exdigits</code> is -1, exponential notation will never
  * be used. If 0 is specified for <code>exdigits</code>, exponential
  * notation is always used unless the exponent would be 0.
  * <p>
  * <code>exform</code> sets the form for exponential notation (if
  * needed).
  * It  may be either {@link MathContext#SCIENTIFIC} or
  * {@link MathContext#ENGINEERING}.
  * If the latter, engineering, form is requested, up to three digits
  * (plus sign, if negative) may be needed for the integer part of the
  * result (<code>before</code>).  Otherwise, only one digit (plus
  * sign, if negative) is needed.
  * <p>
  * Finally, the sixth argument, <code>exround</code>, selects the
  * rounding algorithm to be used, and must be one of the values
  * indicated by a public constant in the {@link MathContext} class
  * whose name starts with <code>ROUND_</code>.
  * The default (<code>ROUND_HALF_UP</code>) may also be selected by
  * using the value -1, as before.
  * <p>
  * The special value <code>MathContext.ROUND_UNNECESSARY</code> may be
  * used to detect whether non-zero digits are discarded -- if
  * <code>exround</code> has this value than if non-zero digits would
  * be discarded (rounded) during formatting then an
  * <code>ArithmeticException</code> is thrown.
  *
  * @param  before   The <code>int</code> specifying the number of places
  *                  before the decimal point.
  *                  Use -1 for 'as many as are needed'.
  * @param  after    The <code>int</code> specifying the number of places
  *                  after the decimal point.
  *                  Use -1 for 'as many as are needed'.
  * @param  explaces The <code>int</code> specifying the number of places
  *                  to be used for any exponent.
  *                  Use -1 for 'as many as are needed'.
  * @param  exdigits The <code>int</code> specifying the trigger
  *                  (digits before the decimal point) which if
  *                  exceeded causes exponential notation to be used.
  *                  Use 0 to force exponential notation.
  *                  Use -1 to force plain notation (no exponential
  *                  notation).
  * @param  exform   The <code>int</code> specifying the form of
  *                  exponential notation to be used
  *                  ({@link MathContext#SCIENTIFIC} or
  *                  {@link MathContext#ENGINEERING}).
  * @param  exround  The <code>int</code> specifying the rounding mode
  *                  to use.
  *                  Use -1 for the default, {@link MathContext#ROUND_HALF_UP}.
  * @return          A <code>String</code> representing this
  *                  <code>BigDecimal</code>, laid out according to the
  *                  specified parameters
  * @throws ArithmeticException if the number cannot be laid out as
  *                  requested.
  * @throws IllegalArgumentException if a parameter is out of range.
  * @see    #toString
  * @see    #toCharArray
  * @stable ICU 2.0
  */
 
 //--public java.lang.String format(int before,int after,int explaces,int exdigits,int exformint,int exround){
 function format() {
  var explaces;
  var exdigits;
  var exformint;
  var exround;
  if (format.arguments.length == 6)
   {
    explaces = format.arguments[2];
    exdigits = format.arguments[3];
    exformint = format.arguments[4];
    exround = format.arguments[5];
   }
  else if (format.arguments.length == 2)
   {
    explaces = -1;
    exdigits = -1;
    exformint = MathContext.prototype.SCIENTIFIC;
    exround = this.ROUND_HALF_UP;
   }
  else
   {
    throw "format(): " + format.arguments.length + " arguments given; expected 2 or 6"
   }
  var before = format.arguments[0];
  var after = format.arguments[1];
  //--com.ibm.icu.math.BigDecimal num;
  var num;
  //--int mag=0;
  var mag=0;
  //--int thisafter=0;
  var thisafter=0;
  //--int lead=0;
  var lead=0;
  //--byte newmant[]=null;
  var newmant=null;
  //--int chop=0;
  var chop=0;
  //--int need=0;
  var need=0;
  //--int oldexp=0;
  var oldexp=0;
  //--char a[];
  var a;
  //--int p=0;
  var p=0;
  //--char newa[]=null;
  var newa=null;
  //--int i=0;
  var i=0;
  //--int places=0;
  var places=0;
  
  
  /* Check arguments */
  if ((before<(-1))||(before==0)) 
   this.badarg("format",1,before);
  if (after<(-1)) 
   this.badarg("format",2,after);
  if ((explaces<(-1))||(explaces==0)) 
   this.badarg("format",3,explaces);
  if (exdigits<(-1)) 
   this.badarg("format",4,exdigits);
  {/*select*/
  if (exformint==MathContext.prototype.SCIENTIFIC)
   ;
  else if (exformint==MathContext.prototype.ENGINEERING)
   ;
  else if (exformint==(-1))
   exformint=MathContext.prototype.SCIENTIFIC;
   // note PLAIN isn't allowed
  else{
   this.badarg("format",5,exformint);
  }
  }
  // checking the rounding mode is done by trying to construct a
  // MathContext object with that mode; it will fail if bad
  if (exround!=this.ROUND_HALF_UP) 
   {try{ // if non-default...
    if (exround==(-1)) 
     exround=this.ROUND_HALF_UP;
    else 
     new MathContext(9,MathContext.prototype.SCIENTIFIC,false,exround);
   }
   catch ($10){
    this.badarg("format",6,exround);
   }}
  
  num=this.clone(this); // make private copy
  
  /* Here:
     num       is BigDecimal to format
     before    is places before point [>0]
     after     is places after point  [>=0]
     explaces  is exponent places     [>0]
     exdigits  is exponent digits     [>=0]
     exformint is exponent form       [one of two]
     exround   is rounding mode       [one of eight]
     'before' through 'exdigits' are -1 if not specified
  */
  
  /* determine form */
  {setform:do{/*select*/
  if (exdigits==(-1))
   num.form=MathContext.prototype.PLAIN;
  else if (num.ind==this.iszero)
   num.form=MathContext.prototype.PLAIN;
  else{
   // determine whether triggers
   mag=num.exp+num.mant.length;
   if (mag>exdigits) 
    num.form=exformint;
   else 
    if (mag<(-5)) 
     num.form=exformint;
    else 
     num.form=MathContext.prototype.PLAIN;
  }
  }while(false);}/*setform*/
  
  /* If 'after' was specified then we may need to adjust the
     mantissa.  This is a little tricky, as we must conform to the
     rules of exponential layout if necessary (e.g., we cannot end up
     with 10.0 if scientific). */
  if (after>=0) 
   {setafter:for(;;){
    // calculate the current after-length
    {/*select*/
    if (num.form==MathContext.prototype.PLAIN)
     thisafter=-num.exp; // has decimal part
    else if (num.form==MathContext.prototype.SCIENTIFIC)
     thisafter=num.mant.length-1;
    else{ // engineering
     lead=(((num.exp+num.mant.length)-1))%3; // exponent to use
     if (lead<0) 
      lead=3+lead; // negative exponent case
     lead++; // number of leading digits
     if (lead>=num.mant.length) 
      thisafter=0;
     else 
      thisafter=num.mant.length-lead;
    }
    }
    if (thisafter==after) 
     break setafter; // we're in luck
    if (thisafter<after) 
     { // need added trailing zeros
      // [thisafter can be negative]
      newmant=this.extend(num.mant,(num.mant.length+after)-thisafter);
      num.mant=newmant;
      num.exp=num.exp-((after-thisafter)); // adjust exponent
      if (num.exp<this.MinExp) 
       throw "format(): Exponent Overflow: " + num.exp;
      break setafter;
     }
    // We have too many digits after the decimal point; this could
    // cause a carry, which could change the mantissa...
    // Watch out for implied leading zeros in PLAIN case
    chop=thisafter-after; // digits to lop [is >0]
    if (chop>num.mant.length) 
     { // all digits go, no chance of carry
      // carry on with zero
      num.mant=this.ZERO.mant;
      num.ind=this.iszero;
      num.exp=0;
      continue setafter; // recheck: we may need trailing zeros
     }
    // we have a digit to inspect from existing mantissa
    // round the number as required
    need=num.mant.length-chop; // digits to end up with [may be 0]
    oldexp=num.exp; // save old exponent
    num.round(need,exround);
    // if the exponent grew by more than the digits we chopped, then
    // we must have had a carry, so will need to recheck the layout
    if ((num.exp-oldexp)==chop) 
     break setafter; // number did not have carry
    // mantissa got extended .. so go around and check again
    }
   }/*setafter*/
  
  a=num.layout(); // lay out, with exponent if required, etc.
  
  /* Here we have laid-out number in 'a' */
  // now apply 'before' and 'explaces' as needed
  if (before>0) 
   {
    // look for '.' or 'E'
    {var $11=a.length;p=0;p:for(;$11>0;$11--,p++){
     if (a[p]=='.') 
      break p;
     if (a[p]=='E') 
      break p;
     }
    }/*p*/
    // p is now offset of '.', 'E', or character after end of array
    // that is, the current length of before part
    if (p>before) 
     this.badarg("format",1,before); // won't fit
    if (p<before) 
     { // need leading blanks
      newa=new Array((a.length+before)-p);
      {var $12=before-p;i=0;i:for(;$12>0;$12--,i++){
       newa[i]=' ';
       }
      }/*i*/
      //--java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,i,a.length);
      this.arraycopy(a,0,newa,i,a.length);
      a=newa;
     }
   // [if p=before then it's just the right length]
   }
  
  if (explaces>0) 
   {
    // look for 'E' [cannot be at offset 0]
    {var $13=a.length-1;p=a.length-1;p:for(;$13>0;$13--,p--){
     if (a[p]=='E') 
      break p;
     }
    }/*p*/
    // p is now offset of 'E', or 0
    if (p==0) 
     { // no E part; add trailing blanks
      newa=new Array((a.length+explaces)+2);
      //--java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,0,a.length);
      this.arraycopy(a,0,newa,0,a.length);
      {var $14=explaces+2;i=a.length;i:for(;$14>0;$14--,i++){
       newa[i]=' ';
       }
      }/*i*/
      a=newa;
     }
    else 
     {/* found E */ // may need to insert zeros
      places=(a.length-p)-2; // number so far
      if (places>explaces) 
       this.badarg("format",3,explaces);
      if (places<explaces) 
       { // need to insert zeros
        newa=new Array((a.length+explaces)-places);
        //--java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,0,p+2); // through E and sign
        this.arraycopy(a,0,newa,0,p+2);
        {var $15=explaces-places;i=p+2;i:for(;$15>0;$15--,i++){
         newa[i]='0';
         }
        }/*i*/
        //--java.lang.System.arraycopy((java.lang.Object)a,p+2,(java.lang.Object)newa,i,places); // remainder of exponent
        this.arraycopy(a,p+2,newa,i,places);
        a=newa;
       }
     // [if places=explaces then it's just the right length]
     }
   }
  return a.join("");
  }

 /**
  * Returns the hashcode for this <code>BigDecimal</code>.
  * This hashcode is suitable for use by the
  * <code>java.util.Hashtable</code> class.
  * <p>
  * Note that two <code>BigDecimal</code> objects are only guaranteed
  * to produce the same hashcode if they are exactly equal (that is,
  * the <code>String</code> representations of the
  * <code>BigDecimal</code> numbers are identical -- they have the same
  * characters in the same sequence).
  *
  * @return An <code>int</code> that is the hashcode for <code>this</code>.
  * @stable ICU 2.0
  */
 
 //--public int hashCode(){
 //-- // Maybe calculate ourselves, later.  If so, note that there can be
 //-- // more than one internal representation for a given toString() result.
 //-- return this.toString().hashCode();
 //-- }

 /**
  * Converts this <code>BigDecimal</code> to an <code>int</code>.
  * If the <code>BigDecimal</code> has a non-zero decimal part it is
  * discarded. If the <code>BigDecimal</code> is out of the possible
  * range for an <code>int</code> (32-bit signed integer) result then
  * only the low-order 32 bits are used. (That is, the number may be
  * <i>decapitated</i>.)  To avoid unexpected errors when these
  * conditions occur, use the {@link #intValueExact} method.
  *
  * @return An <code>int</code> converted from <code>this</code>,
  *         truncated and decapitated if necessary.
  * @stable ICU 2.0
  */
 
 //--public int intValue(){
 //-- return toBigInteger().intValue();
 //-- }

 /**
  * Converts this <code>BigDecimal</code> to an <code>int</code>.
  * If the <code>BigDecimal</code> has a non-zero decimal part or is
  * out of the possible range for an <code>int</code> (32-bit signed
  * integer) result then an <code>ArithmeticException</code> is thrown.
  *
  * @return An <code>int</code> equal in value to <code>this</code>.
  * @throws ArithmeticException if <code>this</code> has a non-zero
  *                 decimal part, or will not fit in an
  *                 <code>int</code>.
  * @stable ICU 2.0
  */
 
 //--public int intValueExact(){
 function intValueExact() {
  //--int lodigit;
  var lodigit;
  //--int useexp=0;
  var useexp=0;
  //--int result;
  var result;
  //--int i=0;
  var i=0;
  //--int topdig=0;
  var topdig=0;
  // This does not use longValueExact() as the latter can be much
  // slower.
  // intcheck (from pow) relies on this to check decimal part
  if (this.ind==this.iszero) 
   return 0; // easy, and quite common
  /* test and drop any trailing decimal part */
  lodigit=this.mant.length-1;
  if (this.exp<0) 
   {
    lodigit=lodigit+this.exp; // reduces by -(-exp)
    /* all decimal places must be 0 */
    if ((!(this.allzero(this.mant,lodigit+1)))) 
     throw "intValueExact(): Decimal part non-zero: " + this.toString();
    if (lodigit<0) 
     return 0; // -1<this<1
    useexp=0;
   }
  else 
   {/* >=0 */
    if ((this.exp+lodigit)>9)  // early exit
     throw "intValueExact(): Conversion overflow: "+this.toString();
    useexp=this.exp;
   }
  /* convert the mantissa to binary, inline for speed */
  result=0;
  {var $16=lodigit+useexp;i=0;i:for(;i<=$16;i++){
   result=result*10;
   if (i<=lodigit) 
    result=result+this.mant[i];
   }
  }/*i*/
  
  /* Now, if the risky length, check for overflow */
  if ((lodigit+useexp)==9) 
   {
    // note we cannot just test for -ve result, as overflow can move a
    // zero into the top bit [consider 5555555555]
    topdig=div(result,1000000000); // get top digit, preserving sign
    if (topdig!=this.mant[0]) 
     { // digit must match and be positive
      // except in the special case ...
      if (result==-2147483648)  // looks like the special
       if (this.ind==this.isneg)  // really was negative
        if (this.mant[0]==2) 
         return result; // really had top digit 2
      throw "intValueExact(): Conversion overflow: "+this.toString();
     }
   }
  
  /* Looks good */
  if (this.ind==this.ispos) 
   return result;
  return -result;
  }

 /**
  * Converts this <code>BigDecimal</code> to a <code>long</code>.
  * If the <code>BigDecimal</code> has a non-zero decimal part it is
  * discarded. If the <code>BigDecimal</code> is out of the possible
  * range for a <code>long</code> (64-bit signed integer) result then
  * only the low-order 64 bits are used. (That is, the number may be
  * <i>decapitated</i>.)  To avoid unexpected errors when these
  * conditions occur, use the {@link #longValueExact} method.
  *
  * @return A <code>long</code> converted from <code>this</code>,
  *         truncated and decapitated if necessary.
  * @stable ICU 2.0
  */
 
 //--public long longValue(){
 //-- return toBigInteger().longValue();
 //-- }

 /**
  * Converts this <code>BigDecimal</code> to a <code>long</code>.
  * If the <code>BigDecimal</code> has a non-zero decimal part or is
  * out of the possible range for a <code>long</code> (64-bit signed
  * integer) result then an <code>ArithmeticException</code> is thrown.
  *
  * @return A <code>long</code> equal in value to <code>this</code>.
  * @throws ArithmeticException if <code>this</code> has a non-zero
  *                 decimal part, or will not fit in a
  *                 <code>long</code>.
  * @stable ICU 2.0
  */
 
 //--public long longValueExact(){
 //-- int lodigit;
 //-- int cstart=0;
 //-- int useexp=0;
 //-- long result;
 //-- int i=0;
 //-- long topdig=0;
 //-- // Identical to intValueExact except for result=long, and exp>=20 test
 //-- if (ind==0) 
 //--  return 0; // easy, and quite common
 //-- lodigit=mant.length-1; // last included digit
 //-- if (exp<0) 
 //--  {
 //--   lodigit=lodigit+exp; // -(-exp)
 //--   /* all decimal places must be 0 */
 //--   if (lodigit<0) 
 //--    cstart=0;
 //--   else 
 //--    cstart=lodigit+1;
 //--   if ((!(allzero(mant,cstart)))) 
 //--    throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
 //--   if (lodigit<0) 
 //--    return 0; // -1<this<1
 //--   useexp=0;
 //--  }
 //-- else 
 //--  {/* >=0 */
 //--   if ((exp+mant.length)>18)  // early exit
 //--    throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
 //--   useexp=exp;
 //--  }
 //-- 
 //-- /* convert the mantissa to binary, inline for speed */
 //-- // note that we could safely use the 'test for wrap to negative'
 //-- // algorithm here, but instead we parallel the intValueExact
 //-- // algorithm for ease of checking and maintenance.
 //-- result=(long)0;
 //-- {int $17=lodigit+useexp;i=0;i:for(;i<=$17;i++){
 //--  result=result*10;
 //--  if (i<=lodigit) 
 //--   result=result+mant[i];
 //--  }
 //-- }/*i*/
 //-- 
 //-- /* Now, if the risky length, check for overflow */
 //-- if ((lodigit+useexp)==18) 
 //--  {
 //--   topdig=result/1000000000000000000L; // get top digit, preserving sign
 //--   if (topdig!=mant[0]) 
 //--    { // digit must match and be positive
 //--     // except in the special case ...
 //--     if (result==java.lang.Long.MIN_VALUE)  // looks like the special
 //--      if (ind==isneg)  // really was negative
 //--       if (mant[0]==9) 
 //--        return result; // really had top digit 9
 //--     throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
 //--    }
 //--  }
 //-- 
 //-- /* Looks good */
 //-- if (ind==ispos) 
 //--  return result;
 //-- return (long)-result;
 //-- }

 /**
  * Returns a plain <code>BigDecimal</code> whose decimal point has
  * been moved to the left by a specified number of positions.
  * The parameter, <code>n</code>, specifies the number of positions to
  * move the decimal point.
  * That is, if <code>n</code> is 0 or positive, the number returned is
  * given by:
  * <p><code>
  * this.multiply(TEN.pow(new BigDecimal(-n)))
  * </code>
  * <p>
  * <code>n</code> may be negative, in which case the method returns
  * the same result as <code>movePointRight(-n)</code>.
  *
  * @param  n The <code>int</code> specifying the number of places to
  *           move the decimal point leftwards.
  * @return   A <code>BigDecimal</code> derived from
  *           <code>this</code>, with the decimal point moved
  *           <code>n</code> places to the left.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal movePointLeft(int n){
 function movePointLeft(n) {
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  // very little point in optimizing for shift of 0
  res=this.clone(this);
  res.exp=res.exp-n;
  return res.finish(this.plainMC,false); // finish sets form and checks exponent
  }

 /**
  * Returns a plain <code>BigDecimal</code> whose decimal point has
  * been moved to the right by a specified number of positions.
  * The parameter, <code>n</code>, specifies the number of positions to
  * move the decimal point.
  * That is, if <code>n</code> is 0 or positive, the number returned is
  * given by:
  * <p><code>
  * this.multiply(TEN.pow(new BigDecimal(n)))
  * </code>
  * <p>
  * <code>n</code> may be negative, in which case the method returns
  * the same result as <code>movePointLeft(-n)</code>.
  *
  * @param  n The <code>int</code> specifying the number of places to
  *           move the decimal point rightwards.
  * @return   A <code>BigDecimal</code> derived from
  *           <code>this</code>, with the decimal point moved
  *           <code>n</code> places to the right.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal movePointRight(int n){
 function movePointRight(n) {
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  res=this.clone(this);
  res.exp=res.exp+n;
  return res.finish(this.plainMC,false);
  }

 /**
  * Returns the scale of this <code>BigDecimal</code>.
  * Returns a non-negative <code>int</code> which is the scale of the
  * number. The scale is the number of digits in the decimal part of
  * the number if the number were formatted without exponential
  * notation.
  *
  * @return An <code>int</code> whose value is the scale of this
  *         <code>BigDecimal</code>.
  * @stable ICU 2.0
  */
 
 //--public int scale(){
 function scale() {
  if (this.exp>=0) 
   return 0; // scale can never be negative
  return -this.exp;
  }

 /**
  * Returns a plain <code>BigDecimal</code> with a given scale.
  * <p>
  * If the given scale (which must be zero or positive) is the same as
  * or greater than the length of the decimal part (the scale) of this
  * <code>BigDecimal</code> then trailing zeros will be added to the
  * decimal part as necessary.
  * <p>
  * If the given scale is less than the length of the decimal part (the
  * scale) of this <code>BigDecimal</code> then trailing digits
  * will be removed, and in this case an
  * <code>ArithmeticException</code> is thrown if any discarded digits
  * are non-zero.
  * <p>
  * The same as {@link #setScale(int, int)}, where the first parameter
  * is the scale, and the second is
  * <code>MathContext.ROUND_UNNECESSARY</code>.
  *
  * @param  scale The <code>int</code> specifying the scale of the
  *               resulting <code>BigDecimal</code>.
  * @return       A plain <code>BigDecimal</code> with the given scale.
  * @throws ArithmeticException if <code>scale</code> is negative.
  * @throws ArithmeticException if reducing scale would discard
  *               non-zero digits.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal setScale(int scale){
 //-- return setScale(scale,ROUND_UNNECESSARY);
 //-- }

 /**
  * Returns a plain <code>BigDecimal</code> with a given scale.
  * <p>
  * If the given scale (which must be zero or positive) is the same as
  * or greater than the length of the decimal part (the scale) of this
  * <code>BigDecimal</code> then trailing zeros will be added to the
  * decimal part as necessary.
  * <p>
  * If the given scale is less than the length of the decimal part (the
  * scale) of this <code>BigDecimal</code> then trailing digits
  * will be removed, and the rounding mode given by the second
  * parameter is used to determine if the remaining digits are
  * affected by a carry.
  * In this case, an <code>IllegalArgumentException</code> is thrown if
  * <code>round</code> is not a valid rounding mode.
  * <p>
  * If <code>round</code> is <code>MathContext.ROUND_UNNECESSARY</code>,
  * an <code>ArithmeticException</code> is thrown if any discarded
  * digits are non-zero.
  *
  * @param  scale The <code>int</code> specifying the scale of the
  *               resulting <code>BigDecimal</code>.
  * @param  round The <code>int</code> rounding mode to be used for
  *               the division (see the {@link MathContext} class).
  * @return       A plain <code>BigDecimal</code> with the given scale.
  * @throws IllegalArgumentException if <code>round</code> is not a
  *               valid rounding mode.
  * @throws ArithmeticException if <code>scale</code> is negative.
  * @throws ArithmeticException if <code>round</code> is
  *               <code>MathContext.ROUND_UNNECESSARY</code>, and
  *               reducing scale would discard non-zero digits.
  * @stable ICU 2.0
  */
 
 //--public com.ibm.icu.math.BigDecimal setScale(int scale,int round){
 function setScale() {
  var round;
  if (setScale.arguments.length == 2)
   {
    round = setScale.arguments[1];
   }
  else if (setScale.arguments.length == 1)
   {
    round = this.ROUND_UNNECESSARY;
   }
  else
   {
    throw "setScale(): " + setScale.arguments.length + " given; expected 1 or 2"
   }
  var scale = setScale.arguments[0];
  //--int ourscale;
  var ourscale;
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  //--int padding=0;
  var padding=0;
  //--int newlen=0;
  var newlen=0;
  // at present this naughtily only checks the round value if it is
  // needed (used), for speed
  ourscale=this.scale();
  if (ourscale==scale)  // already correct scale
   if (this.form==MathContext.prototype.PLAIN)  // .. and form
    return this;
  res=this.clone(this); // need copy
  if (ourscale<=scale) 
   { // simply zero-padding/changing form
    // if ourscale is 0 we may have lots of 0s to add
    if (ourscale==0) 
     padding=res.exp+scale;
    else 
     padding=scale-ourscale;
    res.mant=this.extend(res.mant,res.mant.length+padding);
    res.exp=-scale; // as requested
   }
  else 
   {/* ourscale>scale: shortening, probably */
    if (scale<0) 
     //--throw new java.lang.ArithmeticException("Negative scale:"+" "+scale);
     throw "setScale(): Negative scale: " + scale;
    // [round() will raise exception if invalid round]
    newlen=res.mant.length-((ourscale-scale)); // [<=0 is OK]
    res=res.round(newlen,round); // round to required length
    // This could have shifted left if round (say) 0.9->1[.0]
    // Repair if so by adding a zero and reducing exponent
    if (res.exp!=(-scale)) 
     {
      res.mant=this.extend(res.mant,res.mant.length+1);
      res.exp=res.exp-1;
     }
   }
  res.form=MathContext.prototype.PLAIN; // by definition
  return res;
  }
 
 /**
  * Converts this <code>BigDecimal</code> to a <code>short</code>.
  * If the <code>BigDecimal</code> has a non-zero decimal part or is
  * out of the possible range for a <code>short</code> (16-bit signed
  * integer) result then an <code>ArithmeticException</code> is thrown.
  *
  * @return A <code>short</code> equal in value to <code>this</code>.
  * @throws ArithmeticException if <code>this</code> has a non-zero
  *                 decimal part, or will not fit in a
  *                 <code>short</code>.
  * @stable ICU 2.0
  */
 
 //--public short shortValueExact(){
 //-- int num;
 //-- num=this.intValueExact(); // will check decimal part too
 //-- if ((num>32767)|(num<(-32768))) 
 //--  throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
 //-- return (short)num;
 //-- }

 /**
  * Returns the sign of this <code>BigDecimal</code>, as an
  * <code>int</code>.
  * This returns the <i>signum</i> function value that represents the
  * sign of this <code>BigDecimal</code>.
  * That is, -1 if the <code>BigDecimal</code> is negative, 0 if it is
  * numerically equal to zero, or 1 if it is positive.
  *
  * @return An <code>int</code> which is -1 if the
  *         <code>BigDecimal</code> is negative, 0 if it is
  *         numerically equal to zero, or 1 if it is positive.
  * @stable ICU 2.0
  */
 
 //--public int signum(){
 function signum() {
  return this.ind; // [note this assumes values for ind.]
  }
 
 /**
  * Converts this <code>BigDecimal</code> to a
  * <code>java.math.BigDecimal</code>.
  * <p>
  * This is an exact conversion; the result is the same as if the
  * <code>BigDecimal</code> were formatted as a plain number without
  * any rounding or exponent and then the
  * <code>java.math.BigDecimal(java.lang.String)</code> constructor
  * were used to construct the result.
  * <p>
  * <i>(Note: this method is provided only in the
  * <code>com.ibm.icu.math</code> version of the BigDecimal class.
  * It would not be present in a <code>java.math</code> version.)</i>
  *
  * @return The <code>java.math.BigDecimal</code> equal in value
  *         to this <code>BigDecimal</code>.
  * @stable ICU 2.0
  */
 
 //--public java.math.BigDecimal toBigDecimal(){
 //-- return new java.math.BigDecimal(this.unscaledValue(),this.scale());
 //-- }

 /**
  * Converts this <code>BigDecimal</code> to a
  * <code>java.math.BigInteger</code>.
  * <p>
  * Any decimal part is truncated (discarded).
  * If an exception is desired should the decimal part be non-zero,
  * use {@link #toBigIntegerExact()}.
  *
  * @return The <code>java.math.BigInteger</code> equal in value
  *         to the integer part of this <code>BigDecimal</code>.
  * @stable ICU 2.0
  */
 
 //--public java.math.BigInteger toBigInteger(){
 //-- com.ibm.icu.math.BigDecimal res=null;
 //-- int newlen=0;
 //-- byte newmant[]=null;
 //-- {/*select*/
 //-- if ((exp>=0)&(form==com.ibm.icu.math.MathContext.PLAIN))
 //--  res=this; // can layout simply
 //-- else if (exp>=0)
 //--  {
 //--   res=clone(this); // safe copy
 //--   res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // .. and request PLAIN
 //--  }
 //-- else{
 //--  { // exp<0; scale to be truncated
 //--   // we could use divideInteger, but we may as well be quicker
 //--   if (((int)-this.exp)>=this.mant.length) 
 //--    res=ZERO; // all blows away
 //--   else 
 //--    {
 //--     res=clone(this); // safe copy
 //--     newlen=res.mant.length+res.exp;
 //--     newmant=new byte[newlen]; // [shorter]
 //--     java.lang.System.arraycopy((java.lang.Object)res.mant,0,(java.lang.Object)newmant,0,newlen);
 //--     res.mant=newmant;
 //--     res.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
 //--     res.exp=0;
 //--    }
 //--  }
 //-- }
 //-- }
 //-- return new BigInteger(new java.lang.String(res.layout()));
 //-- }

 /**
  * Converts this <code>BigDecimal</code> to a
  * <code>java.math.BigInteger</code>.
  * <p>
  * An exception is thrown if the decimal part (if any) is non-zero.
  *
  * @return The <code>java.math.BigInteger</code> equal in value
  *         to the integer part of this <code>BigDecimal</code>.
  * @throws ArithmeticException if <code>this</code> has a non-zero
  *         decimal part.
  * @stable ICU 2.0
  */
 
 //--public java.math.BigInteger toBigIntegerExact(){
 //-- /* test any trailing decimal part */
 //-- if (exp<0) 
 //--  { // possible decimal part
 //--   /* all decimal places must be 0; note exp<0 */
 //--   if ((!(allzero(mant,mant.length+exp)))) 
 //--    throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
 //--  }
 //-- return toBigInteger();
 //-- }

 /**
  * Returns the <code>BigDecimal</code> as a character array.
  * The result of this method is the same as using the
  * sequence <code>toString().toCharArray()</code>, but avoids creating
  * the intermediate <code>String</code> and <code>char[]</code>
  * objects.
  *
  * @return The <code>char[]</code> array corresponding to this
  *         <code>BigDecimal</code>.
  * @stable ICU 2.0
  */
 
 //--public char[] toCharArray(){
 //-- return layout();
 //-- }

 /**
  * Returns the <code>BigDecimal</code> as a <code>String</code>.
  * This returns a <code>String</code> that exactly represents this
  * <code>BigDecimal</code>, as defined in the decimal documentation
  * (see {@link BigDecimal class header}).
  * <p>
  * By definition, using the {@link #BigDecimal(String)} constructor
  * on the result <code>String</code> will create a
  * <code>BigDecimal</code> that is exactly equal to the original
  * <code>BigDecimal</code>.
  *
  * @return The <code>String</code> exactly corresponding to this
  *         <code>BigDecimal</code>.
  * @see    #format(int, int)
  * @see    #format(int, int, int, int, int, int)
  * @see    #toCharArray()
  * @stable ICU 2.0
  */
 
 //--public java.lang.String toString(){
 function toString() {
  return this.layout().join("");
  }
 
 /**
  * Returns the number as a <code>BigInteger</code> after removing the
  * scale.
  * That is, the number is expressed as a plain number, any decimal
  * point is then removed (retaining the digits of any decimal part),
  * and the result is then converted to a <code>BigInteger</code>.
  *
  * @return The <code>java.math.BigInteger</code> equal in value to
  *         this <code>BigDecimal</code> multiplied by ten to the
  *         power of <code>this.scale()</code>.
  * @stable ICU 2.0
  */
 
 //--public java.math.BigInteger unscaledValue(){
 //-- com.ibm.icu.math.BigDecimal res=null;
 //-- if (exp>=0) 
 //--  res=this;
 //-- else 
 //--  {
 //--   res=clone(this); // safe copy
 //--   res.exp=0; // drop scale
 //--  }
 //-- return res.toBigInteger();
 //-- }

 /**
  * Translates a <code>double</code> to a <code>BigDecimal</code>.
  * <p>
  * Returns a <code>BigDecimal</code> which is the decimal
  * representation of the 64-bit signed binary floating point
  * parameter. If the parameter is infinite, or is not a number (NaN),
  * a <code>NumberFormatException</code> is thrown.
  * <p>
  * The number is constructed as though <code>num</code> had been
  * converted to a <code>String</code> using the
  * <code>Double.toString()</code> method and the
  * {@link #BigDecimal(java.lang.String)} constructor had then been used.
  * This is typically not an exact conversion.
  *
  * @param  dub The <code>double</code> to be translated.
  * @return     The <code>BigDecimal</code> equal in value to
  *             <code>dub</code>.
  * @throws NumberFormatException if the parameter is infinite or
  *             not a number.
  * @stable ICU 2.0
  */
 
 //--public static com.ibm.icu.math.BigDecimal valueOf(double dub){
 //-- // Reminder: a zero double returns '0.0', so we cannot fastpath to
 //-- // use the constant ZERO.  This might be important enough to justify
 //-- // a factory approach, a cache, or a few private constants, later.
 //-- return new com.ibm.icu.math.BigDecimal((new java.lang.Double(dub)).toString());
 //-- }

 /**
  * Translates a <code>long</code> to a <code>BigDecimal</code>.
  * That is, returns a plain <code>BigDecimal</code> whose value is
  * equal to the given <code>long</code>.
  *
  * @param  lint The <code>long</code> to be translated.
  * @return      The <code>BigDecimal</code> equal in value to
  *              <code>lint</code>.
  * @stable ICU 2.0
  */
 
 //--public static com.ibm.icu.math.BigDecimal valueOf(long lint){
 //-- return valueOf(lint,0);
 //-- }

 /**
  * Translates a <code>long</code> to a <code>BigDecimal</code> with a
  * given scale.
  * That is, returns a plain <code>BigDecimal</code> whose unscaled
  * value is equal to the given <code>long</code>, adjusted by the
  * second parameter, <code>scale</code>.
  * <p>
  * The result is given by:
  * <p><code>
  * (new BigDecimal(lint)).divide(TEN.pow(new BigDecimal(scale)))
  * </code>
  * <p>
  * A <code>NumberFormatException</code> is thrown if <code>scale</code>
  * is negative.
  *
  * @param  lint  The <code>long</code> to be translated.
  * @param  scale The <code>int</code> scale to be applied.
  * @return       The <code>BigDecimal</code> equal in value to
  *               <code>lint</code>.
  * @throws NumberFormatException if the scale is negative.
  * @stable ICU 2.0
  */
 
 //--public static com.ibm.icu.math.BigDecimal valueOf(long lint,int scale){
 //-- com.ibm.icu.math.BigDecimal res=null;
 //-- {/*select*/
 //-- if (lint==0)
 //--  res=ZERO;
 //-- else if (lint==1)
 //--  res=ONE;
 //-- else if (lint==10)
 //--  res=TEN;
 //-- else{
 //--  res=new com.ibm.icu.math.BigDecimal(lint);
 //-- }
 //-- }
 //-- if (scale==0) 
 //--  return res;
 //-- if (scale<0) 
 //--  throw new java.lang.NumberFormatException("Negative scale:"+" "+scale);
 //-- res=clone(res); // safe copy [do not mutate]
 //-- res.exp=(int)-scale; // exponent is -scale
 //-- return res;
 //-- }

 /* ---------------------------------------------------------------- */
 /* Private methods                                                  */
 /* ---------------------------------------------------------------- */
 
 /* <sgml> Return char array value of a BigDecimal (conversion from
       BigDecimal to laid-out canonical char array).
    <p>The mantissa will either already have been rounded (following an
       operation) or will be of length appropriate (in the case of
       construction from an int, for example).
    <p>We must not alter the mantissa, here.
    <p>'form' describes whether we are to use exponential notation (and
       if so, which), or if we are to lay out as a plain/pure numeric.
    </sgml> */
 
 //--private char[] layout(){
 function layout() {
  //--char cmant[];
  var cmant;
  //--int i=0;
  var i=0;
  //--java.lang.StringBuffer sb=null;
  var sb=null;
  //--int euse=0;
  var euse=0;
  //--int sig=0;
  var sig=0;
  //--char csign=0;
  var csign=0;
  //--char rec[]=null;
  var rec=null;
  //--int needsign;
  var needsign;
  //--int mag;
  var mag;
  //--int len=0;
  var len=0;
  cmant=new Array(this.mant.length); // copy byte[] to a char[]
  {var $18=this.mant.length;i=0;i:for(;$18>0;$18--,i++){
   cmant[i]=this.mant[i]+'';
   }
  }/*i*/
  
  if (this.form!=MathContext.prototype.PLAIN) 
   {/* exponential notation needed */
    //--sb=new java.lang.StringBuffer(cmant.length+15); // -x.xxxE+999999999
    sb="";
    if (this.ind==this.isneg) 
     sb += '-';
    euse=(this.exp+cmant.length)-1; // exponent to use
    /* setup sig=significant digits and copy to result */
    if (this.form==MathContext.prototype.SCIENTIFIC) 
     { // [default]
      sb += cmant[0]; // significant character
      if (cmant.length>1)  // have decimal part
       //--sb.append('.').append(cmant,1,cmant.length-1);
       sb += '.';
       sb += cmant.slice(1).join("");
     }
    else 
     {engineering:do{
      sig=euse%3; // common
      if (sig<0) 
       sig=3+sig; // negative exponent
      euse=euse-sig;
      sig++;
      if (sig>=cmant.length) 
       { // zero padding may be needed
        //--sb.append(cmant,0,cmant.length);
        sb += cmant.join("");
        {var $19=sig-cmant.length;for(;$19>0;$19--){
         sb += '0';
         }
        }
       }
      else 
       { // decimal point needed
        //--sb.append(cmant,0,sig).append('.').append(cmant,sig,cmant.length-sig);
        sb += cmant.slice(0,sig).join("");
        sb += '.';
        sb += cmant.slice(sig).join("");
       }
     }while(false);}/*engineering*/
    if (euse!=0) 
     {
      if (euse<0) 
       {
        csign='-';
        euse=-euse;
       }
      else 
       csign='+';
      //--sb.append('E').append(csign).append(euse);
      sb += 'E';
      sb += csign;
      sb += euse;
     }
    //--rec=new Array(sb.length);
    //--Utility.getChars(sb, 0,sb.length(),rec,0);
    //--return rec;
    return sb.split("");
   }
  
  /* Here for non-exponential (plain) notation */
  if (this.exp==0) 
   {/* easy */
    if (this.ind>=0) 
     return cmant; // non-negative integer
    rec=new Array(cmant.length+1);
    rec[0]='-';
    //--java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,1,cmant.length);
    this.arraycopy(cmant,0,rec,1,cmant.length);
    return rec;
   }
  
  /* Need a '.' and/or some zeros */
  needsign=((this.ind==this.isneg)?1:0); // space for sign?  0 or 1
  
  /* MAG is the position of the point in the mantissa (index of the
     character it follows) */
  mag=this.exp+cmant.length;
  
  if (mag<1) 
   {/* 0.00xxxx form */
    len=(needsign+2)-this.exp; // needsign+2+(-mag)+cmant.length
    rec=new Array(len);
    if (needsign!=0) 
     rec[0]='-';
    rec[needsign]='0';
    rec[needsign+1]='.';
    {var $20=-mag;i=needsign+2;i:for(;$20>0;$20--,i++){ // maybe none
     rec[i]='0';
     }
    }/*i*/
    //--java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,(needsign+2)-mag,cmant.length);
    this.arraycopy(cmant,0,rec,(needsign+2)-mag,cmant.length);
    return rec;
   }
  
  if (mag>cmant.length) 
   {/* xxxx0000 form */
    len=needsign+mag;
    rec=new Array(len);
    if (needsign!=0) 
     rec[0]='-';
    //--java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,needsign,cmant.length);
    this.arraycopy(cmant,0,rec,needsign,cmant.length);
    {var $21=mag-cmant.length;i=needsign+cmant.length;i:for(;$21>0;$21--,i++){ // never 0
     rec[i]='0';
     }
    }/*i*/
    return rec;
   }
  
  /* decimal point is in the middle of the mantissa */
  len=(needsign+1)+cmant.length;
  rec=new Array(len);
  if (needsign!=0) 
   rec[0]='-';
  //--java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,needsign,mag);
  this.arraycopy(cmant,0,rec,needsign,mag);
  rec[needsign+mag]='.';
  //--java.lang.System.arraycopy((java.lang.Object)cmant,mag,(java.lang.Object)rec,(needsign+mag)+1,cmant.length-mag);
  this.arraycopy(cmant,mag,rec,(needsign+mag)+1,cmant.length-mag);
  return rec;
  }
 
 /* <sgml> Checks a BigDecimal argument to ensure it's a true integer
       in a given range.
    <p>If OK, returns it as an int. </sgml> */
 // [currently only used by pow]
 
 //--private int intcheck(int min,int max){
 function intcheck(min, max) {
  //--int i;
  var i;
  i=this.intValueExact(); // [checks for non-0 decimal part]
  // Use same message as though intValueExact failed due to size
  if ((i<min)||(i>max)) 
   throw "intcheck(): Conversion overflow: "+i;
  return i;
  }
 
 /* <sgml> Carry out division operations. </sgml> */
 /*
    Arg1 is operation code: D=divide, I=integer divide, R=remainder
    Arg2 is the rhs.
    Arg3 is the context.
    Arg4 is explicit scale iff code='D' or 'I' (-1 if none).
 
    Underlying algorithm (complications for Remainder function and
    scaled division are omitted for clarity):
 
      Test for x/0 and then 0/x
      Exp =Exp1 - Exp2
      Exp =Exp +len(var1) -len(var2)
      Sign=Sign1 * Sign2
      Pad accumulator (Var1) to double-length with 0's (pad1)
      Pad Var2 to same length as Var1
      B2B=1st two digits of var2, +1 to allow for roundup
      have=0
      Do until (have=digits+1 OR residue=0)
        if exp<0 then if integer divide/residue then leave
        this_digit=0
        Do forever
           compare numbers
           if <0 then leave inner_loop
           if =0 then (- quick exit without subtract -) do
              this_digit=this_digit+1; output this_digit
              leave outer_loop; end
           Compare lengths of numbers (mantissae):
           If same then CA=first_digit_of_Var1
                   else CA=first_two_digits_of_Var1
           mult=ca*10/b2b   -- Good and safe guess at divisor
           if mult=0 then mult=1
           this_digit=this_digit+mult
           subtract
           end inner_loop
         if have\=0 | this_digit\=0 then do
           output this_digit
           have=have+1; end
         var2=var2/10
         exp=exp-1
         end outer_loop
      exp=exp+1   -- set the proper exponent
      if have=0 then generate answer=0
      Return to FINISHED
      Result defined by MATHV1
 
    For extended commentary, see DMSRCN.
  */
 
 //--private com.ibm.icu.math.BigDecimal dodivide(char code,com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set,int scale){
 function dodivide(code, rhs, set, scale) {
  //--com.ibm.icu.math.BigDecimal lhs;
  var lhs;
  //--int reqdig;
  var reqdig;
  //--int newexp;
  var newexp;
  //--com.ibm.icu.math.BigDecimal res;
  var res;
  //--int newlen;
  var newlen;
  //--byte var1[];
  var var1;
  //--int var1len;
  var var1len;
  //--byte var2[];
  var var2;
  //--int var2len;
  var var2len;
  //--int b2b;
  var b2b;
  //--int have;
  var have;
  //--int thisdigit=0;
  var thisdigit=0;
  //--int i=0;
  var i=0;
  //--byte v2=0;
  var v2=0;
  //--int ba=0;
  var ba=0;
  //--int mult=0;
  var mult=0;
  //--int start=0;
  var start=0;
  //--int padding=0;
  var padding=0;
  //--int d=0;
  var d=0;
  //--byte newvar1[]=null;
  var newvar1=null;
  //--byte lasthave=0;
  var lasthave=0;
  //--int actdig=0;
  var actdig=0;
  //--byte newmant[]=null;
  var newmant=null;
  
  if (set.lostDigits) 
   this.checkdigits(rhs,set.digits);
  lhs=this; // name for clarity
  
  // [note we must have checked lostDigits before the following checks]
  if (rhs.ind==0) 
   throw "dodivide(): Divide by 0"; // includes 0/0
  if (lhs.ind==0) 
   { // 0/x => 0 [possibly with .0s]
    if (set.form!=MathContext.prototype.PLAIN) 
     return this.ZERO;
    if (scale==(-1)) 
     return lhs;
    return lhs.setScale(scale);
   }
  
  /* Prepare numbers according to BigDecimal rules */
  reqdig=set.digits; // local copy (heavily used)
  if (reqdig>0) 
   {
    if (lhs.mant.length>reqdig) 
     lhs=this.clone(lhs).round(set);
    if (rhs.mant.length>reqdig) 
     rhs=this.clone(rhs).round(set);
   }
  else 
   {/* scaled divide */
    if (scale==(-1)) 
     scale=lhs.scale();
    // set reqdig to be at least large enough for the computation
    reqdig=lhs.mant.length; // base length
    // next line handles both positive lhs.exp and also scale mismatch
    if (scale!=(-lhs.exp)) 
     reqdig=(reqdig+scale)+lhs.exp;
    reqdig=(reqdig-((rhs.mant.length-1)))-rhs.exp; // reduce by RHS effect
    if (reqdig<lhs.mant.length) 
     reqdig=lhs.mant.length; // clamp
    if (reqdig<rhs.mant.length) 
     reqdig=rhs.mant.length; // ..
   }
  
  /* precalculate exponent */
  newexp=((lhs.exp-rhs.exp)+lhs.mant.length)-rhs.mant.length;
  /* If new exponent -ve, then some quick exits are possible */
  if (newexp<0) 
   if (code!='D') 
    {
     if (code=='I') 
      return this.ZERO; // easy - no integer part
     /* Must be 'R'; remainder is [finished clone of] input value */
     return this.clone(lhs).finish(set,false);
    }
  
  /* We need slow division */
  res=new BigDecimal(); // where we'll build result
  res.ind=(lhs.ind*rhs.ind); // final sign (for D/I)
  res.exp=newexp; // initial exponent (for D/I)
  res.mant=this.createArrayWithZeros(reqdig+1); // where build the result
  
  /* Now [virtually pad the mantissae with trailing zeros */
  // Also copy the LHS, which will be our working array
  newlen=(reqdig+reqdig)+1;
  var1=this.extend(lhs.mant,newlen); // always makes longer, so new safe array
  var1len=newlen; // [remaining digits are 0]
  
  var2=rhs.mant;
  var2len=newlen;
  
  /* Calculate first two digits of rhs (var2), +1 for later estimations */
  b2b=(var2[0]*10)+1;
  if (var2.length>1) 
   b2b=b2b+var2[1];
  
  /* start the long-division loops */
  have=0;
  {outer:for(;;){
   thisdigit=0;
   /* find the next digit */
   {inner:for(;;){
    if (var1len<var2len) 
     break inner; // V1 too low
    if (var1len==var2len) 
     { // compare needed
      {compare:do{ // comparison
       {var $22=var1len;i=0;i:for(;$22>0;$22--,i++){
        // var1len is always <= var1.length
        if (i<var2.length) 
         v2=var2[i];
        else 
         v2=0;
        if (var1[i]<v2) 
         break inner; // V1 too low
        if (var1[i]>v2) 
         break compare; // OK to subtract
        }
       }/*i*/
       /* reach here if lhs and rhs are identical; subtraction will
          increase digit by one, and the residue will be 0 so we
          are done; leave the loop with residue set to 0 (in case
          code is 'R' or ROUND_UNNECESSARY or a ROUND_HALF_xxxx is
          being checked) */
       thisdigit++;
       res.mant[have]=thisdigit;
       have++;
       var1[0]=0; // residue to 0 [this is all we'll test]
       // var1len=1      -- [optimized out]
       break outer;
      }while(false);}/*compare*/
      /* prepare for subtraction.  Estimate BA (lengths the same) */
      ba=var1[0]; // use only first digit
     } // lengths the same
    else 
     {/* lhs longer than rhs */
      /* use first two digits for estimate */
      ba=var1[0]*10;
      if (var1len>1) 
       ba=ba+var1[1];
     }
    /* subtraction needed; V1>=V2 */
    mult=div((ba*10),b2b);
    if (mult==0) 
     mult=1;
    thisdigit=thisdigit+mult;
    // subtract; var1 reusable
    var1=this.byteaddsub(var1,var1len,var2,var2len,-mult,true);
    if (var1[0]!=0) 
     continue inner; // maybe another subtract needed
    /* V1 now probably has leading zeros, remove leading 0's and try
       again. (It could be longer than V2) */
    {var $23=var1len-2;start=0;start:for(;start<=$23;start++){
     if (var1[start]!=0) 
      break start;
     var1len--;
     }
    }/*start*/
    if (start==0) 
     continue inner;
    // shift left
    //--java.lang.System.arraycopy((java.lang.Object)var1,start,(java.lang.Object)var1,0,var1len);
    this.arraycopy(var1,start,var1,0,var1len);
    }
   }/*inner*/
   
   /* We have the next digit */
   if ((have!=0)||(thisdigit!=0)) 
    { // put the digit we got
     res.mant[have]=thisdigit;
     have++;
     if (have==(reqdig+1)) 
      break outer; // we have all we need
     if (var1[0]==0) 
      break outer; // residue now 0
    }
   /* can leave now if a scaled divide and exponent is small enough */
   if (scale>=0) 
    if ((-res.exp)>scale) 
     break outer;
   /* can leave now if not Divide and no integer part left  */
   if (code!='D') 
    if (res.exp<=0) 
     break outer;
   res.exp=res.exp-1; // reduce the exponent
   /* to get here, V1 is less than V2, so divide V2 by 10 and go for
      the next digit */
   var2len--;
   }
  }/*outer*/
  
  /* here when we have finished dividing, for some reason */
  // have is the number of digits we collected in res.mant
  if (have==0) 
   have=1; // res.mant[0] is 0; we always want a digit
  
  if ((code=='I')||(code=='R')) 
   {/* check for integer overflow needed */
    if ((have+res.exp)>reqdig) 
     throw "dodivide(): Integer overflow";
    
    if (code=='R') 
     {remainder:do{
      /* We were doing Remainder -- return the residue */
      if (res.mant[0]==0)  // no integer part was found
       return this.clone(lhs).finish(set,false); // .. so return lhs, canonical
      if (var1[0]==0) 
       return this.ZERO; // simple 0 residue
      res.ind=lhs.ind; // sign is always as LHS
      /* Calculate the exponent by subtracting the number of padding zeros
         we added and adding the original exponent */
      padding=((reqdig+reqdig)+1)-lhs.mant.length;
      res.exp=(res.exp-padding)+lhs.exp;
      
      /* strip insignificant padding zeros from residue, and create/copy
         the resulting mantissa if need be */
      d=var1len;
      {i=d-1;i:for(;i>=1;i--){if(!((res.exp<lhs.exp)&&(res.exp<rhs.exp)))break;
       if (var1[i]!=0) 
        break i;
       d--;
       res.exp=res.exp+1;
       }
      }/*i*/
      if (d<var1.length) 
       {/* need to reduce */
        newvar1=new Array(d);
        //--java.lang.System.arraycopy((java.lang.Object)var1,0,(java.lang.Object)newvar1,0,d); // shorten
        this.arraycopy(var1,0,newvar1,0,d);
        var1=newvar1;
       }
      res.mant=var1;
      return res.finish(set,false);
     }while(false);}/*remainder*/
   }
   
  else 
   {/* 'D' -- no overflow check needed */
    // If there was a residue then bump the final digit (iff 0 or 5)
    // so that the residue is visible for ROUND_UP, ROUND_HALF_xxx and
    // ROUND_UNNECESSARY checks (etc.) later.
    // [if we finished early, the residue will be 0]
    if (var1[0]!=0) 
     { // residue not 0
      lasthave=res.mant[have-1];
      if (((lasthave%5))==0) 
       res.mant[have-1]=(lasthave+1);
     }
   }
  
  /* Here for Divide or Integer Divide */
  // handle scaled results first ['I' always scale 0, optional for 'D']
  if (scale>=0) 
   {scaled:do{
    // say 'scale have res.exp len' scale have res.exp res.mant.length
    if (have!=res.mant.length) 
     // already padded with 0's, so just adjust exponent
     res.exp=res.exp-((res.mant.length-have));
    // calculate number of digits we really want [may be 0]
    actdig=res.mant.length-(((-res.exp)-scale));
    res.round(actdig,set.roundingMode); // round to desired length
    // This could have shifted left if round (say) 0.9->1[.0]
    // Repair if so by adding a zero and reducing exponent
    if (res.exp!=(-scale)) 
     {
      res.mant=this.extend(res.mant,res.mant.length+1);
      res.exp=res.exp-1;
     }
    return res.finish(set,true); // [strip if not PLAIN]
   }while(false);}/*scaled*/
  
  // reach here only if a non-scaled
  if (have==res.mant.length) 
   { // got digits+1 digits
    res.round(set);
    have=reqdig;
   }
  else 
   {/* have<=reqdig */
    if (res.mant[0]==0) 
     return this.ZERO; // fastpath
    // make the mantissa truly just 'have' long
    // [we could let finish do this, during strip, if we adjusted
    // the exponent; however, truncation avoids the strip loop]
    newmant=new Array(have); // shorten
    //--java.lang.System.arraycopy((java.lang.Object)res.mant,0,(java.lang.Object)newmant,0,have);
    this.arraycopy(res.mant,0,newmant,0,have);
    res.mant=newmant;
   }
  return res.finish(set,true);
  }
 
 /* <sgml> Report a conversion exception. </sgml> */
 
 //--private void bad(char s[]){
 function bad(prefix, s) {
  throw prefix + "Not a number: "+s;
  }
 
 /* <sgml> Report a bad argument to a method. </sgml>
    Arg1 is method name
    Arg2 is argument position
    Arg3 is what was found */
 
 //--private void badarg(java.lang.String name,int pos,java.lang.String value){
 function badarg(name, pos, value) {
  throw "Bad argument "+pos+" to "+name+": "+value;
  }

 /* <sgml> Extend byte array to given length, padding with 0s.  If no
    extension is required then return the same array. </sgml>
 
    Arg1 is the source byte array
    Arg2 is the new length (longer)
    */
 
 //--private static final byte[] extend(byte inarr[],int newlen){
 function extend(inarr, newlen) {
  //--byte newarr[];
  var newarr;
  if (inarr.length==newlen) 
   return inarr;
  newarr=createArrayWithZeros(newlen);
  //--java.lang.System.arraycopy((java.lang.Object)inarr,0,(java.lang.Object)newarr,0,inarr.length);
  this.arraycopy(inarr,0,newarr,0,inarr.length);
  // 0 padding is carried out by the JVM on allocation initialization
  return newarr;
  }
 
 /* <sgml> Add or subtract two >=0 integers in byte arrays
    <p>This routine performs the calculation:
    <pre>
    C=A+(B*M)
    </pre>
    Where M is in the range -9 through +9
    <p>
    If M<0 then A>=B must be true, so the result is always
    non-negative.
 
    Leading zeros are not removed after a subtraction.  The result is
    either the same length as the longer of A and B, or 1 longer than
    that (if a carry occurred).
 
    A is not altered unless Arg6 is 1.
    B is never altered.
 
    Arg1 is A
    Arg2 is A length to use (if longer than A, pad with 0's)
    Arg3 is B
    Arg4 is B length to use (if longer than B, pad with 0's)
    Arg5 is M, the multiplier
    Arg6 is 1 if A can be used to build the result (if it fits)
 
    This routine is severely performance-critical; *any* change here
    must be measured (timed) to assure no performance degradation.
    */
 // 1996.02.20 -- enhanced version of DMSRCN algorithm (1981)
 // 1997.10.05 -- changed to byte arrays (from char arrays)
 // 1998.07.01 -- changed to allow destructive reuse of LHS
 // 1998.07.01 -- changed to allow virtual lengths for the arrays
 // 1998.12.29 -- use lookaside for digit/carry calculation
 // 1999.08.07 -- avoid multiply when mult=1, and make db an int
 // 1999.12.22 -- special case m=-1, also drop 0 special case
 
 //--private static final byte[] byteaddsub(byte a[],int avlen,byte b[],int bvlen,int m,boolean reuse){
 function byteaddsub(a, avlen, b, bvlen, m, reuse) {
  //--int alength;
  var alength;
  //--int blength;
  var blength;
  //--int ap;
  var ap;
  //--int bp;
  var bp;
  //--int maxarr;
  var maxarr;
  //--byte reb[];
  var reb;
  //--boolean quickm;
  var quickm;
  //--int digit;
  var digit;
  //--int op=0;
  var op=0;
  //--int dp90=0;
  var dp90=0;
  //--byte newarr[];
  var newarr;
  //--int i=0;
  var i=0;
  
  
  
  
  // We'll usually be right if we assume no carry
  alength=a.length; // physical lengths
  blength=b.length; // ..
  ap=avlen-1; // -> final (rightmost) digit
  bp=bvlen-1; // ..
  maxarr=bp;
  if (maxarr<ap) 
   maxarr=ap;
  reb=null; // result byte array
  if (reuse) 
   if ((maxarr+1)==alength) 
    reb=a; // OK to reuse A
  if (reb==null){ 
   reb=this.createArrayWithZeros(maxarr+1); // need new array
   }
  
  quickm=false; // 1 if no multiply needed
  if (m==1) 
   quickm=true; // most common
  else 
   if (m==(-1)) 
    quickm=true; // also common
  
  digit=0; // digit, with carry or borrow
  {op=maxarr;op:for(;op>=0;op--){
   if (ap>=0) 
    {
     if (ap<alength) 
      digit=digit+a[ap]; // within A
     ap--;
    }
   if (bp>=0) 
    {
     if (bp<blength) 
      { // within B
       if (quickm) 
        {
         if (m>0) 
          digit=digit+b[bp]; // most common
         else 
          digit=digit-b[bp]; // also common
        }
       else 
        digit=digit+(b[bp]*m);
      }
     bp--;
    }
   /* result so far (digit) could be -90 through 99 */
   if (digit<10) 
    if (digit>=0) 
     {quick:do{ // 0-9
      reb[op]=digit;
      digit=0; // no carry
      continue op;
     }while(false);}/*quick*/
   dp90=digit+90;
   reb[op]=this.bytedig[dp90]; // this digit
   digit=this.bytecar[dp90]; // carry or borrow
   }
  }/*op*/
  
  if (digit==0) 
   return reb; // no carry
  // following line will become an Assert, later
  // if digit<0 then signal ArithmeticException("internal.error ["digit"]")
  
  /* We have carry -- need to make space for the extra digit */
  newarr=null;
  if (reuse) 
   if ((maxarr+2)==a.length) 
    newarr=a; // OK to reuse A
  if (newarr==null) 
   newarr=new Array(maxarr+2);
  newarr[0]=digit; // the carried digit ..
  // .. and all the rest [use local loop for short numbers]
  //--if (maxarr<10) 
   {var $24=maxarr+1;i=0;i:for(;$24>0;$24--,i++){
    newarr[i+1]=reb[i];
    }
   }/*i*/
  //--else 
   //--java.lang.System.arraycopy((java.lang.Object)reb,0,(java.lang.Object)newarr,1,maxarr+1);
  return newarr;
  }

 /* <sgml> Initializer for digit array properties (lookaside). </sgml>
    Returns the digit array, and initializes the carry array. */
 
 //--private static final byte[] diginit(){
 function diginit() {
  //--byte work[];
  var work;
  //--int op=0;
  var op=0;
  //--int digit=0;
  var digit=0;
  work=new Array((90+99)+1);
  {op=0;op:for(;op<=(90+99);op++){
   digit=op-90;
   if (digit>=0) 
    {
     work[op]=(digit%10);
     BigDecimal.prototype.bytecar[op]=(div(digit,10)); // calculate carry
     continue op;
    }
   // borrowing...
   digit=digit+100; // yes, this is right [consider -50]
   work[op]=(digit%10);
   BigDecimal.prototype.bytecar[op]=((div(digit,10))-10); // calculate borrow [NB: - after %]
   }
  }/*op*/
  return work;
  }

 /* <sgml> Create a copy of BigDecimal object for local use.
    <p>This does NOT make a copy of the mantissa array.
    </sgml>
    Arg1 is the BigDecimal to clone (non-null)
    */
 
 //--private static final com.ibm.icu.math.BigDecimal clone(com.ibm.icu.math.BigDecimal dec){
 function clone(dec) {
  //--com.ibm.icu.math.BigDecimal copy;
  var copy;
  copy=new BigDecimal();
  copy.ind=dec.ind;
  copy.exp=dec.exp;
  copy.form=dec.form;
  copy.mant=dec.mant;
  return copy;
  }

 /* <sgml> Check one or two numbers for lost digits. </sgml>
    Arg1 is RHS (or null, if none)
    Arg2 is current DIGITS setting
    returns quietly or throws an exception */
 
 //--private void checkdigits(com.ibm.icu.math.BigDecimal rhs,int dig){
 function checkdigits(rhs, dig) {
  if (dig==0) 
   return; // don't check if digits=0
  // first check lhs...
  if (this.mant.length>dig) 
   if ((!(this.allzero(this.mant,dig)))) 
    throw "Too many digits: "+this.toString();
  if (rhs==null) 
   return; // monadic
  if (rhs.mant.length>dig) 
   if ((!(this.allzero(rhs.mant,dig)))) 
    throw "Too many digits: "+rhs.toString();
  return;
  }

 /* <sgml> Round to specified digits, if necessary. </sgml>
    Arg1 is requested MathContext [with length and rounding mode]
    returns this, for convenience */
 
 //--private com.ibm.icu.math.BigDecimal round(com.ibm.icu.math.MathContext set){
 //-- return round(set.digits,set.roundingMode);
 //-- }

 /* <sgml> Round to specified digits, if necessary.
    Arg1 is requested length (digits to round to)
            [may be <=0 when called from format, dodivide, etc.]
    Arg2 is rounding mode
    returns this, for convenience
 
    ind and exp are adjusted, but not cleared for a mantissa of zero
 
    The length of the mantissa returned will be Arg1, except when Arg1
    is 0, in which case the returned mantissa length will be 1.
    </sgml>
    */
 
 //private com.ibm.icu.math.BigDecimal round(int len,int mode){
 function round() {
  var len;
  var mode;
  if (round.arguments.length == 2)
   {
    len = round.arguments[0];
    mode = round.arguments[1];
   }
  else if (round.arguments.length == 1)
   {
    var set = round.arguments[0];
    len = set.digits;
    mode = set.roundingMode;
   }
  else
   {
    throw "round(): " + round.arguments.length + " arguments given; expected 1 or 2";
   }
  //int adjust;
  var adjust;
  //int sign;
  var sign;
  //byte oldmant[];
  var oldmant;
  //boolean reuse=false;
  var reuse=false;
  //--byte first=0;
  var first=0;
  //--int increment;
  var increment;
  //--byte newmant[]=null;
  var newmant=null;
  adjust=this.mant.length-len;
  if (adjust<=0) 
   return this; // nowt to do
  
  this.exp=this.exp+adjust; // exponent of result
  sign=this.ind; // save [assumes -1, 0, 1]
  oldmant=this.mant; // save
  if (len>0) 
   {
    // remove the unwanted digits
    this.mant=new Array(len);
    //--java.lang.System.arraycopy((java.lang.Object)oldmant,0,(java.lang.Object)mant,0,len);
    this.arraycopy(oldmant,0,this.mant,0,len);
    reuse=true; // can reuse mantissa
    first=oldmant[len]; // first of discarded digits
   }
  else 
   {/* len<=0 */
    this.mant=this.ZERO.mant;
    this.ind=this.iszero;
    reuse=false; // cannot reuse mantissa
    if (len==0) 
     first=oldmant[0];
    else 
     first=0; // [virtual digit]
   }
  
  // decide rounding adjustment depending on mode, sign, and discarded digits
  increment=0; // bumper
  {modes:do{/*select*/
  if (mode==this.ROUND_HALF_UP)
   { // default first [most common]
    if (first>=5) 
     increment=sign;
   }
  else if (mode==this.ROUND_UNNECESSARY)
   { // default for setScale()
    // discarding any non-zero digits is an error
    if ((!(this.allzero(oldmant,len)))) 
     throw "round(): Rounding necessary";
   }
  else if (mode==this.ROUND_HALF_DOWN)
   { // 0.5000 goes down
    if (first>5) 
     increment=sign;
    else 
     if (first==5) 
      if ((!(this.allzero(oldmant,len+1)))) 
       increment=sign;
   }
  else if (mode==this.ROUND_HALF_EVEN)
   { // 0.5000 goes down if left digit even
    if (first>5) 
     increment=sign;
    else 
     if (first==5) 
      {
       if ((!(this.allzero(oldmant,len+1)))) 
        increment=sign;
       else /* 0.5000 */
        if ((((this.mant[this.mant.length-1])%2))==1) 
         increment=sign;
      }
   }
  else if (mode==this.ROUND_DOWN)
   ; // never increment
  else if (mode==this.ROUND_UP)
   { // increment if discarded non-zero
    if ((!(this.allzero(oldmant,len)))) 
     increment=sign;
   }
  else if (mode==this.ROUND_CEILING)
   { // more positive
    if (sign>0) 
     if ((!(this.allzero(oldmant,len)))) 
      increment=sign;
   }
  else if (mode==this.ROUND_FLOOR)
   { // more negative
    if (sign<0) 
     if ((!(this.allzero(oldmant,len)))) 
      increment=sign;
   }
  else{
   throw "round(): Bad round value: "+mode;
  }
  }while(false);}/*modes*/
  
  if (increment!=0) 
   {bump:do{
    if (this.ind==this.iszero) 
     {
      // we must not subtract from 0, but result is trivial anyway
      this.mant=this.ONE.mant;
      this.ind=increment;
     }
    else 
     {
      // mantissa is non-0; we can safely add or subtract 1
      if (this.ind==this.isneg) 
       increment=-increment;
      newmant=this.byteaddsub(this.mant,this.mant.length,this.ONE.mant,1,increment,reuse);
      if (newmant.length>this.mant.length) 
       { // had a carry
        // drop rightmost digit and raise exponent
        this.exp++;
        // mant is already the correct length
        //java.lang.System.arraycopy((java.lang.Object)newmant,0,(java.lang.Object)mant,0,mant.length);
        this.arraycopy(newmant,0,this.mant,0,this.mant.length);
       }
      else 
       this.mant=newmant;
     }
   }while(false);}/*bump*/
  // rounding can increase exponent significantly
  if (this.exp>this.MaxExp) 
   throw "round(): Exponent Overflow: "+this.exp;
  return this;
  }

 /* <sgml> Test if rightmost digits are all 0.
    Arg1 is a mantissa array to test
    Arg2 is the offset of first digit to check
            [may be negative; if so, digits to left are 0's]
    returns 1 if all the digits starting at Arg2 are 0
 
    Arg2 may be beyond array bounds, in which case 1 is returned
    </sgml> */
 
 //--private static final boolean allzero(byte array[],int start){
 function allzero(array, start) {
  //--int i=0;
  var i=0;
  if (start<0) 
   start=0;
  {var $25=array.length-1;i=start;i:for(;i<=$25;i++){
   if (array[i]!=0) 
    return false;
   }
  }/*i*/
  return true;
  }
 
 /* <sgml> Carry out final checks and canonicalization
    <p>
    This finishes off the current number by:
      1. Rounding if necessary (NB: length includes leading zeros)
      2. Stripping trailing zeros (if requested and \PLAIN)
      3. Stripping leading zeros (always)
      4. Selecting exponential notation (if required)
      5. Converting a zero result to just '0' (if \PLAIN)
    In practice, these operations overlap and share code.
    It always sets form.
    </sgml>
    Arg1 is requested MathContext (length to round to, trigger, and FORM)
    Arg2 is 1 if trailing insignificant zeros should be removed after
         round (for division, etc.), provided that set.form isn't PLAIN.
   returns this, for convenience
   */
 
 //--private com.ibm.icu.math.BigDecimal finish(com.ibm.icu.math.MathContext set,boolean strip){
 function finish(set, strip) {
  //--int d=0;
  var d=0;
  //--int i=0;
  var i=0;
  //--byte newmant[]=null;
  var newmant=null;
  //--int mag=0;
  var mag=0;
  //--int sig=0;
  var sig=0;
  /* Round if mantissa too long and digits requested */
  if (set.digits!=0) 
   if (this.mant.length>set.digits) 
    this.round(set);
  
  /* If strip requested (and standard formatting), remove
     insignificant trailing zeros. */
  if (strip) 
   if (set.form!=MathContext.prototype.PLAIN) 
    {
     d=this.mant.length;
     /* see if we need to drop any trailing zeros */
     {i=d-1;i:for(;i>=1;i--){
      if (this.mant[i]!=0) 
       break i;
      d--;
      this.exp++;
      }
     }/*i*/
     if (d<this.mant.length) 
      {/* need to reduce */
       newmant=new Array(d);
       //--java.lang.System.arraycopy((java.lang.Object)this.mant,0,(java.lang.Object)newmant,0,d);
       this.arraycopy(this.mant,0,newmant,0,d);
       this.mant=newmant;
      }
    }
  
  this.form=MathContext.prototype.PLAIN; // preset
  
  /* Now check for leading- and all- zeros in mantissa */
  {var $26=this.mant.length;i=0;i:for(;$26>0;$26--,i++){
   if (this.mant[i]!=0) 
    {
     // non-0 result; ind will be correct
     // remove leading zeros [e.g., after subtract]
     if (i>0) 
      {delead:do{
       newmant=new Array(this.mant.length-i);
       //--java.lang.System.arraycopy((java.lang.Object)this.mant,i,(java.lang.Object)newmant,0,this.mant.length-i);
       this.arraycopy(this.mant,i,newmant,0,this.mant.length-i);
       this.mant=newmant;
      }while(false);}/*delead*/
     // now determine form if not PLAIN
     mag=this.exp+this.mant.length;
     if (mag>0) 
      { // most common path
       if (mag>set.digits) 
        if (set.digits!=0) 
         this.form=set.form;
       if ((mag-1)<=this.MaxExp) 
        return this; // no overflow; quick return
      }
     else 
      if (mag<(-5)) 
       this.form=set.form;
     /* check for overflow */
     mag--;
     if ((mag<this.MinExp)||(mag>this.MaxExp)) 
      {overflow:do{
       // possible reprieve if form is engineering
       if (this.form==MathContext.prototype.ENGINEERING) 
        {
         sig=mag%3; // leftover
         if (sig<0) 
          sig=3+sig; // negative exponent
         mag=mag-sig; // exponent to use
         // 1999.06.29: second test here must be MaxExp
         if (mag>=this.MinExp) 
          if (mag<=this.MaxExp) 
           break overflow;
        }
       throw "finish(): Exponent Overflow: "+mag;
      }while(false);}/*overflow*/
     return this;
    }
   }
  }/*i*/
  
  // Drop through to here only if mantissa is all zeros
  this.ind=this.iszero;
  {/*select*/
  if (set.form!=MathContext.prototype.PLAIN)
   this.exp=0; // standard result; go to '0'
  else if (this.exp>0)
   this.exp=0; // +ve exponent also goes to '0'
  else{
   // a plain number with -ve exponent; preserve and check exponent
   if (this.exp<this.MinExp) 
    throw "finish(): Exponent Overflow: "+this.exp;
  }
  }
  this.mant=this.ZERO.mant; // canonical mantissa
  return this;
  }


var rpcCallback = "nullCallback(data)";
var credentialData = "";
var reqData;
var rpcPath;
var timeOutRPCId = "";
var MaxSendCount = 2;
var Timeout_Seconds = 15;
var PROCESS_RPCDATA_ENABLED = false;
var rpcdPool = {
					pool: new Array(),
					push: function (rpcd)
							{
									this.pool[rpcd.id] = rpcd;
							},
					pull: function (rpcd)
							{
								if(rpcd != null && rpcd != undefined)
									this.pool[rpcd.id] = null;
							},
					check: function (rpcd)
							{
								try
								{
									return this.pool[rpcd.id] != null && this.pool[rpcd.id] != undefined && this.pool[rpcd.id] != "";
								}catch(err){return false;}	
							},
					checkId: function (rpcd)
							{
								return rpcd.id != undefined && rpcd.id != null && rpcd.id != "";
							}
							
			   };


function RPCData(){
	this.id = "";
	this.reqData = "";
	this.rpcPath = "";
	this.rpcCallback = "nullCallback(data)";
	this.timeout = Timeout_Seconds * 1000;
	this.credentialData = "";
	this.sended = 0;
	this.operation = "";
	this.vars = new Array();
}
function callRPC(rpcd){
	if(rpcd == null){
		rpcd = new RPCData();
		rpcd.reqData = reqData;
		rpcd.rpcPath = rpcPath;
		rpcd.rpcCallback = rpcCallback;
		rpcd.credentialData = credentialData;
	}
	
	if(rpcdPool.checkId(rpcd))
	{
		if(rpcdPool.check(rpcd))
			return ;
			
		rpcdPool.push(rpcd);
	}
	
	if(PROCESS_RPCDATA_ENABLED)
		callRPCd(rpcd);
	else
		callRPCq(rpcd);
}
function callRPCq(rpcd){
	if(rpcd.needshowload != false){
		try{
			popuper.showLoading();
		}catch(err){
			try{
				popupPage.showLoading();
			}catch(err){}
		}
	}
	var firstRPCId = "";
	if(timeOutRPCId != ""){
		firstRPCId = timeOutRPCId;
	}else{
		firstRPCId = new UUID();
	}
	var rpcData;
	rpcData  = "<RPCRequest>";
	rpcData += "<RPCId>"+ firstRPCId +"</RPCId>";
	rpcData += "<Credential>"+ rpcd.credentialData +"</Credential>";
	rpcData += "<RequestData><Path>"+rpcd.rpcPath+"</Path>"+rpcd.reqData+"</RequestData>";
	rpcData += "</RPCRequest>";
	rpcd.rpcCallback=rpcd.rpcCallback.replace("(data)","");
	var evalstr = "";
	  evalstr += rpcd.rpcPath+".callRPC(rpcData,";
	  evalstr += "{ "; 
	  //evalstr += "callback:"+rpcd.rpcCallback+", ";
	  evalstr += "callback:function(d) {if(rpcd.needshowload!=false){try{popuper.hideLoading();}catch(err){popupPage.hideLoading();}} rpcdPool.pull(rpcd); "+rpcd.rpcCallback+"(d,rpcd);},";
	  evalstr += "timeout:"+rpcd.timeout+", ";
	  evalstr += "errorHandler:function(message) {processingRpcError(message,firstRPCId,rpcd);try{popuper.hideLoading();}catch(err){popupPage.hideLoading();}} ";
	  evalstr += " } ) ";
    eval(evalstr);
}
function processingRpcError(message,rpcId,rpcd){
	if(message == 'Timeout'){
		timeOutRPCId = rpcId;
	//	callRPCq(rpcd);
	}
	
	rpcdPool.pull(rpcd);
}
function nullCallback(){
}
var mailloginPage = "";
function goToMailLoginPage(){
    if(mailloginPage!="" && mailloginPage != null)
		window.open(mailloginPage);
}
function onCallbackError_CheckMemberActive(dataDOM){
    var res = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/NoActive");
    mailloginPage = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/loginPage");
    if(res != "null" && null != res ){
   	 	popwin().showMsg(res,'','goToMailLoginPage;popupPage.closePage()',2);
    }else{
   	 	var er = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label");
  	 	popwin().showMsg(er,'','',2);
  }
}
//中文
function $(elementid)
{  
	var obj;
	try
	{
		obj = document.getElementById(elementid);
	}
	catch (err)
	{
		alert(elementid+" NOT Found!","System");
	}
	return obj;
}

function $ud(str){
	if(str==undefined||str==null||str=="null")return""
	return str;
}

function getRadioValue(rName)
{
	var rObj = document.getElementsByName(rName);
	for ( var i=0; i<rObj.length; i++ )
	{
		if ( rObj[i].checked )
		{
			return rObj[i].value;
		}
	}
	return null;
}

function setRadioValue(rName , val)
{
	var rObj = document.getElementsByName(rName);
	for ( var i=0; i<rObj.length; i++ )
	{
			rObj[i].checked = rObj[i].value == val;
	}
	return null;
}


function areaFormat(country,state,city,spchar)
{
	if(spchar == null) spchar = "&nbsp;,&nbsp;";
	
	
	if(country == null || country == "" || country == "null")
		country = "";
		
	if(state == null || state == "" || state == "null")
		state = "";
	else
		state = state + spchar;
		
	if(city == null || city == ""|| city == "null")
		city = "";
	else
		city = city + spchar;
	
	return city + state +  country;
}


function array_has(val)
 {
  var i;
  for(i = 0; i < this.length; i++)
  {
   if(this[i] == val)
   {
	return true;
   }
  }
  return false;
 }
Array.prototype.contain = array_has;


function getFormElementsXML(formid,pre){
	var items=document.getElementById(formid).elements;
	var hadadd=[];
	var itemi;
	var data="";
	var prename="";
	var preid="";
	for(var n=0; n<items.length;n++){
		itemi=items[n];
		prename = itemi.name.substring(0,pre.length);
		preid = itemi.id.substring(0,pre.length);
		//1.input
		if(itemi.type=="text"){
			if(preid==pre && !hadadd.contain(itemi.id)){
				hadadd.push(itemi.id);
				var temp_value = itemi.value;
				try{
				if(itemi.id.indexOf(pre+"offer")>-1)// just for updateARewardRequest.jsp
				{
					temp_value = temp_value.floatValue();
				}}catch(e){}
				data+="<"+itemi.id+">"+safeXMLChar(temp_value)+"</"+itemi.id+">";
			}
		}
		//2.select
		else if(itemi.type=="select-one"){
			if(preid==pre && !hadadd.contain(itemi.id)){
				hadadd.push(itemi.id);
				data+="<"+itemi.id+">"+safeXMLChar(itemi.value)+"</"+itemi.id+">";
			}
		}
		//3.radio
		else if(itemi.type=="radio"){
			if(prename==pre && !hadadd.contain(itemi.name)){
				hadadd.push(itemi.name);
				data+="<"+itemi.name+">"+safeXMLChar(getRadioValue(itemi.name))+"</"+itemi.name+">";
			}
		}
		//4.textarea
		else if(itemi.type=="textarea"){
			if(preid==pre && !hadadd.contain(itemi.id)){
				hadadd.push(itemi.id);
				data+="<"+itemi.id+">"+safeXMLChar(itemi.value)+"</"+itemi.id+">";
			}
		}
		
	}
	return data;
}

function setRecordToElement(record, map){
	var id="";
	var etype="";
	for(var n=0;n<map.length;n++){
		id=map[n][1];
		if(document.getElementById(id).type=="text"){
			eval("document.getElementById(id).value = record."+map[n][0]+";");
		}else{
			eval("document.getElementById(id).innerHTML = record."+map[n][0]+";");
		}
	}
}


function getBodyObj() 
{
	var e=document.documentElement;
	var _t = {};
	_t.clientHeight = e.clientHeight;
	_t.clientWidth = e.clientWidth;
	
	_t.scrollLeft=e.scrollLeft;
	_t.scrollTop=e.scrollTop;
	
	_t.offsetWidth=e.offsetWidth;
	_t.offsetHeight=e.offsetHeight;
	
	_t.scrollHeight = e.scrollHeight;
	_t.scrollWidth = e.scrollWidth;
	
	if(checkBrowser()==3){
		_t.scrollLeft=document.body.scrollLeft;
		_t.scrollTop=document.body.scrollTop;
	}
    return _t; 
}


function setSelect(eid,evalue)
{
	var sObj = $(eid);
	for ( var i=0; i<sObj.length; i++ )
	{
		if ( sObj[i].value==evalue )
		{
			sObj[i].selected = true;
		}
	}
}
function removeSelect(eid,evalue)
	{
		var sObj = $(eid);
		for ( var i=0; i<sObj.length; i++ )
		{
			if ( sObj[i].value==evalue )
			{
				sObj[i]=null;
				break;
			}
		}
	}
	

function setSelectList(objid, arrayvar, arrvalue)
{
	var objlen = $(objid).options.length;
	if ( arrvalue==null )
	{
		arrvalue = new Array();
		for ( var j=0; j<arrayvar.length; j++ )
		{
			arrvalue[j] = j+1;
		}
	}	
	
	for ( var i=0+objlen,x=0; i<arrayvar.length+objlen; i++,x++ )
	{
		//option begin at 0
		
		if(arrayvar[x]=="")
		{
			i--;
			objlen--;
		}
		else
		{
			$(objid).options[i] = new Option(arrayvar[x],arrvalue[x]); //value begin at 1
		}
	}
}

function getSelectedText(objid){
	var text="";
	try{
		text=$(objid).options[$(objid).selectedIndex].text;
	}catch(err){
		text="";
	}
	return text;
}



function removeAllOptions(objid)
{
	var obj = $(objid);
	var browsernum = checkBrowser();
	if ( browsernum==2 || browsernum == 3) //firefox and google
	{
		obj.length = 0;
	}
	else
	{
		try
		{
			while(obj.options[0] != null)
			{
				obj.options.removeChild(obj.options[0]);  
			}
		}
		catch(err)
		{
		}
	}
}

	function checkBrowser()
	{		
		if ( navigator.userAgent.indexOf("MSIE")>0 )
			return 1;
		if ( isFirefox=navigator.userAgent.indexOf("Firefox")>0 )
			return 2;
		if ( isSafari=navigator.userAgent.indexOf("Safari")>0 ) //google
			return 3;
		if ( isCamino=navigator.userAgent.indexOf("Camino")>0 )
			return 4;
		if ( isMozilla=navigator.userAgent.indexOf("Gecko/")>0)
			return 5;
		return 0;
	}
	
	RegExp.escape = function(text) {
	  if (!arguments.callee.sRE) {
	    var specials = [
	      '/', '.', '*', '+', '?', '|',
	      '(', ')', '[', ']', '{', '}', '\\'
	    ];
	    arguments.callee.sRE = new RegExp(
	      '(\\' + specials.join('|\\') + ')', 'g'
	    );
	  }
	  return text.replace(arguments.callee.sRE, '\\$1');
	}
	
	String.prototype.trim = function(){
    	var value = this.replace(/(^\s*)|(\s*$)/g, "");   
    	return value.replace(/(^　*)|(　*$)/g, "");   
	}
	
	String.prototype.replaceAll = function(oldstr,newstr)
	{
		oldstr=RegExp.escape(oldstr);
		return this.replace(new RegExp(oldstr,"gmi"),newstr);
	}
	
	
	var FontSize = 
	{
		Big : 20 ,
		Medium : 16 ,
		Small : 12 
	}
	function setFontSize(oid , size )
    {
        var divBody = document.getElementById(oid);
        if(!divBody)
        {
            return;
        }
        divBody.style.fontSize = size + "px";
        var divChildBody = divBody.childNodes;
        for(var i = 0; i < divChildBody.length; i++)
        {
            if (divChildBody[i].nodeType==1)
            {
                divChildBody[i].style.fontSize = size + "px";
            }
        }
    }
    
    String.prototype.isContainGB = function ()
	{
		var re=/[\x00-\xff]/g;
		var len=this.length;
		var array=this.match(re);
		if(array!=null && array.length==len){
			return false;
		}
		else{
			return true;
		}
	}
	
    String.prototype.trim = function(isTrimGB)
	{
		return Trim(this,isTrimGB);
	}
	
	String.prototype.entityToText = function()
	{
		return EntitiesToText(this);
	}
		 
	 function EntitiesToText(strEncodedText) 
	 {
		 var strData = String(strEncodedText);
		 var objRegExp = new RegExp("&#(\\d+);", "ig");
	
		 while(strData.match(objRegExp)) {
			 var strCharMatch = RegExp.$1;
			 var objRegExpMatch = new RegExp("&#" + strCharMatch + ";", "ig");
			 strData = strData.replace(objRegExpMatch, String.fromCharCode(strCharMatch));
		 }
		 
	 	 return strData;
	 }
	
    function Trim(obj , isTrimGB)
	{
		if(isTrimGB == null) isTrimGB = false;
		
		if(!isTrimGB)
			return obj.replace(/(^\s*)|(\s*$)/g, "");
		else
			return TrimGB(obj);
			
	}
	function TrimGB(obj){
		if(obj == null || obj == "") return "";
		var str = obj.replace(/(^\s*)|(\s*$)/g, "");
		var kg = "　";
		var start = 0;
		var end = 0;
		var isAllspace = true;
		for(var i = 0;i<str.length ;i++){
			if(str.charAt(i) != kg && str.charAt(i) != ""){
				start = i;
				isAllspace = false;
				break;
			}
		}
		if(isAllspace) return "";
		if(start != 0 ) str = str.substring(start);
		for(var i = str.length-1; i>=0 ;i--){
			if(str.charAt(i) != kg && str.charAt(i) != ""){
				end = i+1;
				break;
			}
		}
		if(end != 0) str = str.substring(0,end);

		return str;
	}
	
	
	//============================Check Form==========================//
	function isNull( str )
	{
		if ( str == "" ) return true;
		
		var regu = "^[ ]+$";
		
		var re = new RegExp(regu);
		
		return re.test(str);
		
		}
		
	  function isInteger( str ){ 

		var regu = /^[-]{0,1}[0-9]{1,}$/;
	
		return regu.test(str);
	
		}
	function isNumber( s ){  //check +num

		var regu = /^[0-9]+$/;
		
		return regu.test(s);
	}
	function isFloat( s , n )
	{  
		if(n == null)
			n = 2;
		var regu = "^[0-9]+[\.][0-9]{0,"+n+"}$";
	
		var re = new RegExp(regu);
	
		if (re.test(s)) {
				return true;
	
		} else {
	
		return false;

		}

	}
	
	function isMoney( s )
	{  
		if(s.indexOf("0.") != 0 && s.indexOf("0") == 0 && s.length > 1)
			return false;
		var inte = s.substring(0,s.indexOf(".") != -1 ? s.indexOf("."):s.length);
		var regu = "^[0-9]+[\.][0-9]{0,2}$"; //  2 decimal^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$
	
		var re = new RegExp(regu);
	  
		if ((re.test(s) || isNumber(s)) && inte.length < 9) 
		{
		      
				return true;
		}
		return false;

	}

	function isNumberOrLetter( s )
	{
		var regu = "^[0-9a-zA-Z\\s]+$";
		
		var re = new RegExp(regu);
		
		if (re.test(s)) {
		
		return true;
		
		}else{
		
		return false;
		
		}
	}

	function isEmail(str)
	{
		var myReg = /^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]*)*@[a-zA-Z0-9\-]+([\.][a-zA-Z0-9\-]+)+$/;
		if ( myReg.test(str) )
			return true;
		return false;
	}

	function isChOrNumOrLetter(s)
	{
		var regu = "^[0-9a-zA-Z\\s\u4e00-\u9fa5]+$";  
		var re = new RegExp(regu);
		if ( re.test(s) )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function isDateTime(sDate)
	{   
		var iaMonthDays = [31,28,31,30,31,30,31,31,30,31,30,31];
	    var iaDate = new Array(3);
	    var year, month, day;
	
	    if (arguments.length != 1) return false;
	    iaDate = sDate.toString().split("-");
	    if (iaDate.length != 3) return false;
	    if (iaDate[1].length > 2|| iaDate[1].length<1|| iaDate[2].length > 2|| iaDate[2].length <1) return false;
	
	    year = parseFloat(iaDate[0]);
	    month = parseFloat(iaDate[1]);
	    day=parseFloat(iaDate[2]);
	
	    if (year < 1900 || year > 2100) return false;
	    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1]=29;
	    if (month < 1 || month > 12) return false;
	    if (day < 1 || day > iaMonthDays[month - 1]) return false;
	    return true;
	} 
	function isMobil(s)  
	 {  
	 var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;  
	 if (!patrn.exec(s)) return false  
	 return true  
	 }
	function isTel(s)  
	 {  
	 //var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?(\d){1,12})+$/;  
	 var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;  
	 if (!patrn.exec(s)) return false  
	 return true  
	 } 
	 function isBankAccount(s)  
	 {  
	 var patrn=/^[\d\-\s]+$/; 
	 if (!patrn.exec(s)) return false  
	 return true  
	 }
	function isPostalCode(s)  
	{  
	 	//var patrn=/^[a-zA-Z0-9]{3,12}$/;  
	 	var patrn=/^[a-zA-Z0-9 ]{3,12}$/;  
	 	if (!patrn.exec(s)) return false  
	 	return true  
	}  
	//============================Check Form End==========================//
	
	String.prototype.getLength = function (isGB)
	{ 
		return getLength(this);
	}
	
	Number.prototype.getLength = function (isGB)
	{ 
		return getLength(this+"");
	}
	
	String.prototype.getSubstring = function (len , rex)
	{ 
		var str = this;
		if(this.indexOf("'") == 0 && this.lastIndexOf("'") == getLength(this) - 1){
			
			 str = this.substring(1,getLength(this)-1);
		}
		if(getLength(str) > len)
		{
			if(rex == null) rex = "···";

			return str.substring(0 , len-5)+rex+this.substring(str.length-5,str.length);
		} 
		else
			return str+"";
	}
	
	
	function getLength(str)
	{	
		//var re=/[\x00-\xff]/g;
		var len=str.length;
		//var array=str.match(re);
		if(!str.isContainGB()){
			return len;
		}
		else{
			return len*2;
		}
	}
	
	                                      
	function safeXMLChar(str)
	{
		if ( str==null )
		{
			return "";
		}
	
		var tempstr = str;
		try
		{
		  	str = str.replace(/&/g,'&amp;');
			str = str.replace(/</g,'&lt;');
			str = str.replace(/>/g,'&gt;');
			str = str.replace(/'/g,'&apos;');
			str = str.replace(/\"/g,'&quot;');
		}
		catch(err)
		{
			return tempstr;
		}
		return str;
	}
	
	
	function safeHTMLChar(str)
	{
		if (str==null)
			return "";
		
		var tempstr=str;
		try
		{
			str = str.replace(/&lt;/g,'<');
			str = str.replace(/&gt;/g,'>');
			str = str.replace(/&apos;/g,'\'');
			str = str.replace(/&quot;/g,'\"');
			str = str.replace(/&nbsp;/g,' ');
		  	str = str.replace(/&amp;/g,'&');
		  	str = str.replace(/&hellip;/g,'...');
		  	str = str.replace(/&#13;/g,'\r\n');
		  	str = str.replace(/&ldquo;/g,'\"');
		  	str = str.replace(/&rdquo;/g,'\"');
		  	str = str.replace(/&mdash;/g,'-');
		  	str = str.replace(/&bull;/g,'•');
		  	str = str.replace(/&lsquo;/g,'‘');
		  	//str = str.replace(/&hellip;/g,'…');
		  	str = str.replace(/&euro;/g,'€');
		  	str = str.replace(/&middot;/g,'·');
		}
		catch(err)
		{
			return tempstr;
		}
	
		
		return str;
	}
	
	
	
	
	//////////////////////////////////////////////////////////
	/////               Javascript Number + - * /
	/////////////////////////////////////////////////////////
	function accSub(arg1,arg2)
	{
		try
		{
			arg1 += "";
			arg2 += "";
			var p1 = new BigDecimal(arg1.trim());
			var p2 = new BigDecimal(arg2.trim());
			return p1.subtract(p2);
		}catch(err)
		{
			return new BigDecimal("0");
		}
	}

	function accDiv(arg1,arg2)
	{ 
		try
		{
			arg1 += "";
			arg2 += "";
			var p1 = new BigDecimal(arg1.trim());
			var p2 = new BigDecimal(arg2.trim());
			return p1.divide(p2,8,BigDecimal.prototype.ROUND_HALF_UP);
		}catch(err)
		{
			return new BigDecimal("0");
		}
	} 
	function accMul(arg1,arg2) 
	{ 
		try
		{
			arg1 += "";
			arg2 += "";
			var p1 = new BigDecimal(arg1.trim());
			var p2 = new BigDecimal(arg2.trim());
			return p1.multiply(p2);
		}catch(err)
		{
			return new BigDecimal("0");
		}
	} 
	function accAdd(arg1,arg2)
	{
		try
		{
			arg1 += "";
			arg2 += "";
			var p1 = new BigDecimal(arg1.trim());
			var p2 = new BigDecimal(arg2.trim());
			return p1.add(p2);
		}catch(err)
		{
			return new BigDecimal("0");
		}	
	}
	Number.prototype.add = function (arg){ 
		return accAdd(arg,this).toString() * 1; 
	}
	Number.prototype.div = function (arg){ 
		return accDiv(this, arg).toString() * 1; 
	} 
	Number.prototype.mul = function (arg){ 
		return accMul(arg, this).toString() * 1; 
	}
	Number.prototype.sub = function (arg){ 
		return accSub(this , arg).toString() * 1; 
	} 
	Number.prototype.percent = function (arg){
		return accMul(accDiv(this,arg) ,100).toString() * 1; 
	}
	Number.prototype.percentby = function (arg){
		return accDiv(accMul(this , arg),100).toString() * 1; 
	}
	Number.prototype.percentby = function (arg){
		return accDiv(accMul(this , arg),100).toString() * 1; 
	}
	//------------------Money In,Out------------------------------
	
	String.prototype.toInmoney = function (arg){ 
		if(arg == null) arg = 2;
		var p1 = new BigDecimal(this.trim());
		p1 = p1.setScale(arg , p1.ROUND_CEILING);
		return p1.toString(); 
	}
	String.prototype.toOutmoney = function (arg){ 
		if(arg == null) arg = 2;
		var p1 = new BigDecimal(this.trim());
		p1 = p1.setScale(arg , p1.ROUND_DOWN);
		return p1.toString(); 
	}
	Number.prototype.toInmoney = function (arg){ 
		var tmp = this+"";
		return tmp.toInmoney(arg);
	}
	Number.prototype.toOutmoney = function (arg){ 
		var tmp = this+"";
		return tmp.toOutmoney(arg);
	}
	String.prototype.toMoney = function (arg){ 
		var n = isNaN(this.replaceAll(",","")*1) == true ? 0 : this.replaceAll(",","")*1 ;
		return n.toOutmoney(arg);
	}
	Number.prototype.toMoney = function (arg){ 
		var tmp = this+"";
		return tmp.toOutmoney(arg);
	}
	String.prototype.toHalfup = function (arg){ 
		if(arg == null) arg = 2;
		var p1 = new BigDecimal(this.trim());
		p1 = p1.setScale(arg , p1.ROUND_HALF_UP);
		return p1.toString(); 
	}
	Number.prototype.toHalfup = function (arg){ 
		var tmp = this+"";
		return tmp.toHalfup(arg);
	}
	//------------------Money In,Out------------------------------End
	
	function formatThousands(s)
	{
		try
		{	
			var isLesszero = false;
			if(s*1 < 0) isLesszero = true;
			
			s = Math.abs(s).toString();
	        if(/[^0-9\.]/.test(s)) return "invalid value";
	        
	        s=s.replace(/^(\d*)$/,"$1.");
	        s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
	        s=s.replace(".",",");
	        var re=/(\d)(\d{3},)/;
	        while(re.test(s))
	                s=s.replace(re,"$1,$2");
	        s=s.replace(/,(\d\d)$/,".$1");
	        if(isLesszero)	
	        	return "-"+s.replace(/^\./,"0.");
	        else
	        	return s.replace(/^\./,"0.");
	     }
	     catch(err)
	     {
	     	return "invalid value";
	     }
     }
    Number.prototype.currencyValue = function ()
    {
    	return formatThousands(this);
    }
    String.prototype.currencyValue = function ()
    {
    	return formatThousands(this.floatValue());
    }

	String.prototype.floatValue = function(arg)
	{
			var n = isNaN(this.replaceAll(",","")*1) == true ? 0 : this.replaceAll(",","")*1 ;
			return n.floatValue(arg);
	}
	Number.prototype.floatValue = function(arg)
	{
		if(arg == null) arg = 2;
		var p1 = new BigDecimal(this+"");
		p1 = p1.setScale(arg , p1.ROUND_DOWN);
		return p1.toString()*1;
	}
	//=========================================End=====================================//
	
	
	String.prototype.toBoolean = function (arg){ 
		if(this.trim().toLowerCase() == "true")
			return true;
		else
		//if(this.trim().toLowerCase() == "false")
			return false;
		//else
		//	return null;
	}
	
	function switchDisplay(objid,exevent)
	{
		$(objid).style.display = ($(objid).style.display=="none") ? "" : "none";
		if ( $(objid).style.display=="" )
		{
			if($(objid).getAttribute("overRpc")=="undefine" || $(objid).getAttribute("overRpc")=="" || $(objid).getAttribute("overRpc")==null)	
			{
				$(objid).setAttribute("overRpc",true);
				try
				{
					eval(exevent);
				}
				catch (err)
				{
				}
			}
		}
	}
	function switchValue(objid,text1,text2){
		var oldText=$(objid).value;
		$(objid).value=(oldText==text1)?text2:text1;
	}
	

	function getCheckBoxValue(cName)
	{
		var s = document.getElementsByName(cName);
		var s2 = "";
		for ( var i=0; i<s.length; i++ )
		{
			if ( s[i].checked )
			{
				s2 += s[i].value+',';
			}
		}
		s2 = s2.substr(0,s2.length-1);
		return s2;
	}	
	
	function setElementDisplay(objid,isshow)
	{
	    
		try
		{
			$(objid).style.display=(isshow)?"":"none";
		}catch(err){
			//alert(objid+" couldn't find!");
		}
	}
	
	function setRadioValueDisabled (rName){
  		var rObj = document.getElementsByName(rName);
 		for(var i = 0 ; i< rObj.length; i++){
     		rObj[i].disabled= true;
  	}

	}
	
	function setElementsDisplay(objids,isshows)
	{
		for(var i=0;i<objids.length;i++){
			try{
				setElementDisplay(objids[i],isshows[i]);
			}catch(err){
			
			}
		}
	}
	
	function setElementsDisplayByName(name,isshow)
	{
		var s = document.getElementsByName(name);
	
		for ( var i=0; i<s.length; i++ )
		{
			try
			{
				s[i].style.display=(isshow)?"":"none";
			}catch(err)
			{}
		}
	}	
	
	function getBytesLength(str) {
		return str.replace(/[^\x00-\xff]/g, 'xx').length;
	}
	
	function getLength(str)
	{	
		//var re=/[\x00-\xff]/g;
		var len=str.length;
		//var array=str.match(re);
		if(!str.isContainGB()){
			return len;
		}
		else{
			return len*2;
		}
	}
	String.prototype.isContainGB = function ()
	{
		var re=/[\x00-\xff]/g;
		var len=this.length;
		var array=this.match(re);
		if(array!=null && array.length==len){
			return false;
		}
		else{
			return true;
		}
	}
	
	String.prototype.getLength = function (isGB)
	{ 
		return getLength(this);
	}
	
	
	function getTagOnSubmit(objId) //use in post 
	{
		var tags = $(objId).value.trim().split(" ");
		var tagRlt = "";
		
		if(tags.length >1)
		{
			for(var i=0;i<tags.length-1;i++)
			{
				var tag = tags[i];
				var isSame = false;
				for(var j=i+1;j<tags.length;j++)
				{
					var tag2 = tags[j];
				
					if(tag == tag2)
					{
						isSame = true;
						break;
					}	
				}
				
				if(!isSame)
					tagRlt += tag+" ";
				if(i==tags.length-2)
					tagRlt += tags[i+1]+" ";	
			}
		}
		else
		{
			tagRlt = tags[0];
		}
		
		return tagRlt;
	}
	
	function formatMoney(amount) {
	amount -= 0;
	var r = "";
	if (amount < 1) {
		r = amount;
	} else {
		if (amount >= 1 && amount < 10000) {
			r = Math.floor(amount);
		} else {
			if (amount >= 10000) {
				r = round(amount / 10000 ,1) + "\u4e07";
			}
		}
	}
	return r;
}
function setRadioCheck(rName,value)
{
	var rObj = document.getElementsByName(rName);
	for ( var i=0; i<rObj.length; i++ )
	{
		if ( rObj[i].value==value )
		{
			rObj[i].checked = true;
			return;
		}
	}
}

	function formatToHtml(str){
		if(str==undefined||str==null)return "";
		str = str.replaceAll("\r\n","<br/>");
		str = str.replaceAll("\n","<br/>");
		str = str.replaceAll("$#13;","<br/>");
		var re=/(\s)\s/gi; 
		str = str.replace(re, "$1&nbsp;");
		str = str.replaceAll("	"," &nbsp; &nbsp; &nbsp;");	//format "TAB"
		return str;
	}
	
		function createExpries(objid)
		{
			var dhm="";
			dhm += "<select tabindex=6 id='timeD' size=1>";
			for ( var i=0; i<30; i++ )
			{
				dhm+="<option>"+i+"</option>";
			}
			dhm += "</select>"+common_system_state_day; 
			
			dhm += "<select tabindex=7 id='timeH' size=1>";
			for ( var i=0; i<25; i++ )
			{
				dhm+="<option>"+i+"</option>";
			}
			dhm += "</select>"+common_system_state_hours;
	
			dhm += "<select tabindex=8 id='timeM' size=1>";
			for ( var i=0; i<61; i++ )
			{
				dhm += "<option>"+i+"</option>";
			}
			dhm += "</select> "+common_system_state_min;
			document.getElementById(objid).innerHTML = dhm;
			document.getElementById("timeD").selectedIndex = 29;
		}
		
		var NumberUtil = {
						ROUND_NO:0,
						ROUND_CEILING:1,
						ROUND_FLOOR:2
					 }
		
		function pointNum(str,n,roundval)
		{
			if(roundval == null) 
				roundval = NumberUtil.ROUND_NO;
			var s = str + "";
			var len =s.length;
			var p=s.indexOf(".");
			var r;
			if(p>0){
				var afterP=len-p-1;
				if(afterP>2){
					r=s.substring(0,p+n+1);
					try{
						switch(roundval)
						{
							case NumberUtil.ROUND_NO :
											//eval("r=("+r+").add(1/Math.pow(10,n));");
											break;
							case NumberUtil.ROUND_CEILING :
											//eval("r=("+r+").add(1/Math.pow(10,n));");								
											//r = Math.ceil(r);
											if(r.floatValue()!=str.floatValue()){
												eval("r=("+r+").add(1/Math.pow(10,n));");
											}
											break;
							case NumberUtil.ROUND_FLOOR :
											eval("r=("+r+").add(1/Math.pow(10,n));");
											r = Math.floor(r);
											break;
						}
					
					}catch(err){
					}
				}else{
					r=s;
				}
			}else{
				r=s;
			}
			return r;
		}
		
function replaceFmt(fmt,c,arg1){
	var str=fmt;
	str=str.replace(c,arg1);
	document.write(str);
}
	Array.prototype.add = function(obj)
	{
		this.push(obj);
	}		
		
	
	function getChatUrl(toid,isshow){
		var v=true;
		if(!isshow){
			v=false;
		}
		if(toid.toString()==currentLoginID.toString()){
			v=false;
		}
		
		if(v){
			//return "<a href='"+WebRoot+"/GenCometURL"+channelChat_pre+"?memberID="+toid+"' target='_blank' title=''><img src='"+scheme+"://"+cometdServer+"/"+cometdProName+"/MemberStatusServlet?memberID="+toid+"' border=\"0\" vspace=\"4\" align=absmiddle /></a>";
			return "<a href='javascript:void(0);'><img src='"+WebRoot+"/images/offline.gif?v=201007121651' border='0' align='absmiddle' /></a>";
		}
		else{
			return "";
		}
	}
	
	function getSelectArrayValue(eid)
	{
		var selstr="";
		var obj = document.getElementById(eid);
		var valary = new Array();
		for( var i=0; i<obj.options.length; i++ )
		{
			valary[i] = obj.options[i].value ;
		}
		return valary;
	}

	function URIEncode(str){
		return encodeURIComponent(str);
	}
	
	function switchImg(obj,img1,img2,viewDiv1)
	{
		var imgPath = "images/";
		if(img1.indexOf("http:")>-1 ||img1.indexOf("https:")>-1){
			imgPath="";
		}
		if(obj.src.indexOf(img1) >-1)
		{
				obj.src = imgPath+img2;
			document.getElementById(viewDiv1).style.display = "";
		}
		else
		{
			obj.src = imgPath+img1;
			document.getElementById(viewDiv1).style.display = "none";
		}
	}
	
	function openDiv(pic,divObj){
			var divo = document.getElementById(divObj);
    		divo.style.display = (divo.style.display=="none") ? "" : "none";
    		if(divo.style.display==""){
    			pic.src = "images/icon-minus.gif?v=201007121651";
    		}else{
    			pic.src = "images/icon-add.gif?v=201007121651";
    		}
		}
		
	function SetHome(obj,vrl){
        try{
                obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
        }
        catch(e){
                if(window.netscape) {
                        try {
                                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                        }
                        catch (e) {
                                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将 [signed.applets.codebase_principal_support]的值设置为'true',双击即可。");
                        }
                        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                        prefs.setCharPref('browser.startup.homepage',vrl);
                 }
        }
}
 
function popwin(){
	try{
		return popuper;
	}catch(err){
		try{
			return popupPage;
		}catch(err){
			alert("POP is null");
		}
	}
}

function debugObj(obj) { 
   var props = ""; 
    for(var p in obj){  
       if(typeof(obj[p])=="function"){  
           obj[p](); 
       }else{  
           props+= p + "=" + obj[p] + "\t"; 
       }  
   }  
  alert(props); 
} 

function jsSepcChar(str){
	if ( str==null )
	{
		return "";
	}
	var tempstr = str;
	try
	{
		str=str.replaceAll("\n"," ");
		str=str.replaceAll("&","&amp;");
		str=str.replaceAll("<","&lt;");
		str=str.replaceAll(">","&gt;");
		str=str.replaceAll("'","\\\'");
	}
	catch(err)
	{
		return tempstr;
	}
	return str;	
}	

function setImgMaxWidth(imgobj,m){
	if(imgobj.width>m){
		imgobj.width=m;
	}	
}

	//---force open window ---------------------//
	function ForceWindow()
	{
		this.r = document.documentElement;
		this.f = document.createElement("FORM");
		this.f.target = "_blank";
		this.f.method = "post";
		this.r.insertBefore(this.f, this.r.childNodes[0]);
	}
	
	ForceWindow.prototype.open = function (sUrl)
	{
		this.f.action = sUrl;
		this.f.submit();
	}
	
	function sessionTimeOutAction(){
		alert(authorized_false_tip);
		window.parent.location.reload();
	}
	
	function UrlEncode(str)
	{ 
	    var ret=""; 
	    var strSpecial="!\"#$%&()*+,/:;<=>?[]^`{|}~%"; var tt="";
	    for(var i=0;i<str.length;i++)
	    { 
	        var chr = str.charAt(i); 
	        var c=str2asc(chr); 
	        tt += chr+":"+c+"n"; 
	        if(parseInt("0x"+c) > 0x7f)
	        { 
	            ret+="%"+c.slice(0,2)+"%"+c.slice(-2); 
	        }
	        else
	        { 
	            if(chr==" ") 
	                ret+="+"; 
	            else if(strSpecial.indexOf(chr)!=-1) 
	                ret+="%"+c.toString(16); 
	            else 
	                ret+=chr; 
	        } 
	    } 
	    return ret; 
	} 

	function UrlDecode(str){ 
	    var ret=""; 
	    for(var i=0;i<str.length;i++)
	    { 
	        var chr = str.charAt(i); 
	        if(chr == "+")
	        { 
	            ret+=" "; 
	        }
	        else if(chr=="%")
	        { 
	            var asc = str.substring(i+1,i+3); 
	            if(parseInt("0x"+asc)>0x7f)
	            { 
	                ret+=asc2str(parseInt("0x"+asc+str.substring(i+4,i+6))); 
	                i+=5; 
	            }
	            else
	            { 
	                ret+=asc2str(parseInt("0x"+asc)); 
	                i+=2; 
	            } 
	        }
	        else
	        { 
	            ret+= chr; 
	        } 
	    } 
	    return ret; 
	} 
	
	function call_smack_chat(memberid,membername){
		try{
			if( !hasLogin() ){
				popuper.showMsg(member_login_notyet,"",'',2);
			}else{
				Smack_csOpenChat(memberid,membername);
			}
		}catch(err){
			   	popuper.showDialog(member_comet_notyet,"",common_system_state_yesorno[0]+" | "+common_system_state_yesorno[1],"gotoSendMsg("+memberid+")");
		}
	}
	function gotoSendMsg(memberid){
		window.location.href = WebRoot+"/member/myInternalMes.jsp?senderID="+memberid;
	}
	
	
	function DOMAddInnerHTML(iid,str){
		var divo = document.createElement("div");
		divo.innerHTML = str;
		$(iid).appendChild(divo);
	}
	
	function FormatNumber(srcStr,nAfterDot)        //nAfterDot小数位数
	{
		var tarStr = "";
		srcStr=srcStr+"";
		var docpos = srcStr.lastIndexOf(".");
		if(docpos == -1 && nAfterDot > 0){
			
			tarStr = srcStr+".";
			for(var i = 0 ; i < nAfterDot; i++){
				tarStr = tarStr+"0";
			}
			return tarStr;
		}else if(docpos == -1){
			return srcStr;
		}else{
			var sufix = "";
			var lengthafterdot = srcStr.length - docpos;
			if(lengthafterdot > nAfterDot){
				return srcStr.substring(0,docpos+nAfterDot);
			}else{
				var len = nAfterDot - lengthafterdot;
				tarStr = srcStr;
				for( var i = 0 ; i < len; i++){
					tarStr = tarStr+"0";
				}
				return tarStr;
			}
		}
	} 
	
	function isIE6(){
		var isIE6=false;
		document.write("<!--[if lte IE 6]><script>isIE6=true;</scr"+"ipt><![endif]-->");
		return isIE6;
	}

function UUID(){
	this.id = this.createUUID();
}
UUID.prototype.valueOf = function(){ return this.id; }
UUID.prototype.toString = function(){ return this.id; }
UUID.prototype.createUUID = function(){
	var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
	var dc = new Date();
	var t = dc.getTime() - dg.getTime();
	var h = '-';
	var tl = UUID.getIntegerBits(t,0,31);
	var tm = UUID.getIntegerBits(t,32,47);
	var thv = UUID.getIntegerBits(t,48,59) + '1';
	var csar = UUID.getIntegerBits(UUID.rand(4095),0,7);
	var csl = UUID.getIntegerBits(UUID.rand(4095),0,7);
	var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,15);
	return tl + h + tm + h + thv + h + csar + csl + h + n; 
}
UUID.getIntegerBits = function(val,start,end){
	var base16 = UUID.returnBase(val,16);
	var quadArray = new Array();
	var quadString = '';
	var i = 0;
	for(i=0;i<base16.length;i++){
		quadArray.push(base16.substring(i,i+1));	
	}
	for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
		if(!quadArray[i] || quadArray[i] == '') quadString += '0';
		else quadString += quadArray[i];
	}
	return quadString;
}
UUID.returnBase = function(number, base){
	return (number).toString(base).toUpperCase();
}
UUID.rand = function(max){
	return Math.floor(Math.random() * (max + 1));
}
var XMLTools = new XMLParser();

var  isIE  =   !! document.all;
if(!isIE){
	HTMLElement.prototype.__defineGetter__("children", 
	     function () { 
	         var returnValue = new Object(); 
	         var number = 0; 
	         for (var i=0; i<this.childNodes.length; i++) { 
	             if (this.childNodes[i].nodeType == 1) { 
	                 returnValue[number] = this.childNodes[i]; 
	                 number++; 
	             } 
	         } 
	         returnValue.length = number; 
	         return returnValue; 
	     } 
	 ); 
	
	if( document.implementation.hasFeature("XPath", "3.0") ) 
	{ 
	   // prototying the XMLDocument 
	   XMLDocument.prototype.selectNodes = function(cXPathString, xNode) 
	   { 
	      if( !xNode ) { xNode = this; }  
	      var oNSResolver = this.createNSResolver(this.documentElement) 
	      var aItems = this.evaluate(cXPathString, xNode, oNSResolver,  
	                   XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null) 
	      var aResult = []; 
	      for( var i = 0; i < aItems.snapshotLength; i++) 
	      { 
	         aResult[i] =  aItems.snapshotItem(i); 
	      } 
	      return aResult; 
	   } 
	
	   // prototying the Element 
	   Element.prototype.selectNodes = function(cXPathString) 
	   { 
	      if(this.ownerDocument.selectNodes) 
	      { 
	         return this.ownerDocument.selectNodes(cXPathString, this); 
	      } 
	      else{throw "For XML Elements Only";} 
	   } 
	} 
}
function XMLParser(){
	this.xmlStr;
	this.isSucceed;
	this.err;
	this.dataDOMTmp;
	this.parseXML = function(data){
		//data = data.replaceAll("\r\n","<!--br-->");
		//data = data.replaceAll("\n","<!--br-->");parse /r;
		//data = data.replaceAll("\"","'");
		
		this.xmlStr = data;
		return this.createResponseXML(data);
	}
	
	this.createResponseXML = function(data){
		var responseXML;
		if(document.all)
		{
			var xmlDom=new ActiveXObject("Microsoft.XMLDOM");
			xmlDom.loadXML(data);
			responseXML =  xmlDom;
		}
		else
		{
			responseXML =  new DOMParser().parseFromString(data, "text/xml");
		}
		return responseXML;
	}
	
	this.selectString = function(dataDOM,xpath){
		var str="";
		var nodes ;
		try{
			nodes = dataDOM.selectNodes(xpath);
		}catch(err){
			return null;
		}

		if( nodes.length==0  )
		{
			return null;
		}
		
		try{
			str=nodes[0].childNodes[0].nodeValue;
		}catch(err)
		{}
		
		return str;
	}
	
	this.recordsFromXML = function(nodes){
		var xmlDataArray=new Array();
		for(var i=0;i<nodes.length;i++){
			var childNodes=nodes[i].childNodes;
			var p={};
			var pStr="";
			var thisEval="";
			for(var n=0;n<childNodes.length;n++){
				try{
					var tmpV=childNodes[n].childNodes[0].nodeValue;
					tmpV=tmpV.replaceAll("&#13;","\n");
					thisEval="p."+childNodes[n].nodeName+"=tmpV;";
					eval(thisEval);
					//pStr +=thisEval;
				}catch(err){
					try
					{
						thisEval="p."+childNodes[n].nodeName+"= \"\";";
						//pStr +=thisEval;
						eval(thisEval);
					}catch(err1)
					{}
				}
				
			}
			//pStr+="xmlDataArray.push(p);";
			xmlDataArray.push(p);
			//eval(pStr);
		}
		return xmlDataArray;
	}
	
	this.removeFirstCDATA = function(data){
		data=data.replace("<![CDATA[","");
		data=data.replace("]]>","");
		return data;
	}
	
	this.parseData = function(data){
		timeOutRPCId = "";
		var dataDOM = this.parseXML(data);
		this.dataDOMTmp = dataDOM;
		var authorized = this.selectString(dataDOM, "//RPCResponse/Authorized");
		if ( authorized=="false" )
		{
			sessionTimeOutAction();
			return;
		}
		var respData = this.selectString(dataDOM, "//RPCResponse/ResponseData/Label/success");
		this.isSucceed = (respData == 'true');
		this.err = ( this.isSucceed ? "" :  this.selectString(dataDOM, "//RPCResponse/ResponseData/Label"));
		return this;
	}
	
	this.getString = function(strpath){
		return this.selectString(this.dataDOMTmp, "//RPCResponse/ResponseData/Label/"+strpath);
	}
	
	this.getDatas = function(strpath){
		var nodes = this.dataDOMTmp.selectNodes("//RPCResponse/ResponseData/Label/"+strpath);
		 var datas = this.recordsFromXML(nodes);
		 return datas;
	}

}


/*
  function ****_Callback(data){
		var r = XMLTools.parseData(data);
		if( r.isSucceed ){
			var c=r.getString("itemID");
			alert( c );
			//var datas=r.getDatas("List/ds");
			
		}else{
			popuper.showMsg(r.err,"",'',0);
		}
  } 
*/

if(common_this_should_iffill==undefined){
	window.common_this_should_iffill = "若选填，长度应为";
}
if(common_this_must_be_filled==undefined){
	window.common_this_must_be_filled = "必须填写此项";
}
if(common_this_should_contain==undefined){
	window.common_this_should_contain = "长度应为";
}
if(common_at_least==undefined){
	window.common_at_least = "至少";
}
if(common_up_to==undefined){
	window.common_up_to = "不多于";
}
if(common_characters==undefined){
	window.common_characters = "个英文字符。";
}
if(common_gbcharacters==undefined){
	window.common_gbcharacters = "个字符。";
}

var softkeyboardEnable  = true; 
////////////////////////////
////Echecker
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function Elemt(eid)
{
	this.elemtID = eid ;
	this.isError = false;
	this.elemtType ;
	this.checkType = 0;
	this.ableEmpty = false;
	this.disabled = false; 
	this.emptyErrMessage = common_this_must_be_filled;
	this.checkErrMessage = "&nbsp;";  //html
	this.extendCheckErrMessage = null;  //html
	this.elemtErrClass = "inputErr";
	this.tipErrorClass = "Input_ErrorTip";
	this.minLength = 0;
	this.maxLength = -1;
	this.errID = this.elemtID + "Err";
	this.isCheckErrMessage = true;
	this.BLUR_EVENT = true ;
	this.KEYUP_EVENT = true ;
	this.softboardEnable = true;
	this.checkGB = false;  //true时，把中文字当前2个字符来算，例: maxLength为3, "一二三"这组字不通过，因为字符串被当成6个字符　;　
						   //false时，无论中英文都会按一个字来算，例: maxLength为3, "一二三"这组字可通过，因为字符串被当成3个字符
	this.ableZero = false;
	this.overStep = false; //如果maxlength = 2000时 ,内容全是en,即以maxlength*2来计算最大长度 
	this.caption = "";
	this.errorMsg = "";  //当前错误信息
	{
		try
		{
				if( $(eid).maxlength != undefined && $(eid).maxlength != "")
					this.maxLength = $(eid).maxlength;
		}
		catch(err)
		{
			//alert("No such Elemt ID : "+eid );
			//return ;
		}
	}
	this.afterOnKeyup = function()
	{
		
	}
	this.afterOnBlur = function()
	{
		
	}
	this.getObject = function()
	{
		return $(this.elemtID)
	}
	
	this.extendCheck = function()  // please overried
	{
		return true;
	}
	
	this.clearError = function ()
	{
		this.isError = false;
		try
		{
			$(this.errID).innerHTML = "";
			if(this.tipErrorClass == $(this.errID).className || this.elemtErrClass  == $(this.errID).className)
				$(this.errID).className = "";
		}
		catch (err)
		{}
	}
	
	this.onCheckErrorFocus = function () //please override , 当提交时check到其中一个elmt有错便执行其elmt相应的操作
	{
	 	//do something
	}
}

var CheckType =
{
	No : 0 ,   // no check
	Email : 1 ,
	Money : 2 ,
	NumberOrLetter : 3 ,  // "3f"
	Number : 4 ,          // "2"
	ChOrNumOrLetter : 5 ,
	Float : 6  ,
	DateTime:	7  ,
	Password:	8  ,
	Radio:   9 , 
	UBB: 10, 
	Tel: 11,
	TelOrMobile: 12,
	PostCode: 13,
	BankAccount: 14
}

		
function ElemtChecker(fid,subfun)
{
	this.elemtary = new Array();
	this.isError = false;
	this.formID = fid;
	this.submitEvent = null;
	this.submitBtn = null;
	
	this.initChecker = function()
	{
		//------init checker -------//
		if(subfun != null)
			this.submit = subfun;
		
		if(this.formID == null)
			this.formID = "frm";  // default ID : "frm"
		(
			function(ecer) 
			{
				var frm = $(ecer.formID);
				if(frm != null)
				frm.onkeydown  = function(event) {  
													var eve = event || window.event;
													var src = eve.target || eve.srcElement;
													if ( eve.keyCode==13 && src.tagName!="TEXTAREA" )
													{
														 ecer.submit(); 
													} 
													
												 }   //set event
			}
		)(this);
		
		

		//-----init elmt -------//
		for(var i=0; i<this.elemtary.length ; i++)  
		{	
			try
			{
				//this.elemtary[i].getObject().value = "";
				//$(this.elemtary[i].errID).innerHTML = "&nbsp;";
			}
			catch(err)
			{}
			
			if(this.elemtary[i].checkType == CheckType.UBB)
			{
				this.elemtary[i].checkGB = true;  //default checkGB 
			}
			
			if(this.elemtary[i].checkType == CheckType.Money || this.elemtary[i].checkType == CheckType.Number)
			{
				this.elemtary[i].getObject().style.textAlign = "left"; //modify
			}
			
			if(this.elemtary[i].checkType == CheckType.Password)
			{
				//this.elemtary[i].getObject().size = 16;
				this.elemtary[i].getObject().setAttribute("maxLength",50);
				this.elemtary[i].maxLength = 16;
				this.elemtary[i].minLength = 6;
				  
				//-----------------softkeyboard-------------------------
				if(softkeyboardEnable && this.elemtary[i].softboardEnable && false)
				{
					this.elemtary[i].BLUR_EVENT = false;
					this.elemtary[i].KEYUP_EVENT = false;
					this.elemtary[i].getObject().onclick= function () { 
																		password1=this;
																		this.readOnly=1;
																		
																		 if(IS_POPUP_PAGE)
																		 {
																			 window.parent.showkeyboard(this);
																			 window.parent.Calc.password.value='';
																		 }
																		 else
																		 {
																			 showkeyboard(this);
																			 Calc.password.value='';
																		 }
																	
															 };
					this.elemtary[i].getObject().onkeyup= function (event) { 
																	evt = event?event:window.event;
																		if(evt.keyCode==9)
																		{
																				password1=this;
																				this.readOnly=1;
																				if(IS_POPUP_PAGE)
																				 {
																					 window.parent.showkeyboard(this);
																					 window.parent.Calc.password.value='';
																				 }
																				 else
																				 {
																					 showkeyboard(this);
																					 Calc.password.value='';
																				 }
																		} 
																	
															};
					
					(
					function(ec,i) 
					{											
						ec.elemtary[i].getObject().onkeydown= function (event) { 
												
																		var eve = event || window.event;
																		if ( eve.keyCode==13)
																		{
																			if(ec.submitBtn != null && ( ec.submitBtn.disabled != true || ec.submitBtn.disabled == undefined))
																			{
																				 ec.submitBtn.onclick(); 
																			}
																			else
																			if(ec.submitEvent != null)
																			{
																				 ec.submitEvent(); 
																			}
																			
																		} 
																};
					}
					)(this,i);
					
				}
				//-----------------softkeyboard--------End-----------------										
						
			}
			;
			(
			function(eve,i) 
			{	
				if(eve.elemtary[i].checkType == CheckType.Radio || eve.elemtary[i].checkType == CheckType.UBB)
					return ;
					
				var elt = $(eve.elemtary[i].elemtID) 
				elt.setAttribute("elemtindex",i);
				
				if(eve.elemtary[i].BLUR_EVENT)
					elt.onblur  = function() {  
													if(eve.elemtary[i].checkType == CheckType.Money)  // format the money
													{
														try
														{
															eve.elemtary[i].getObject().value =  eve.elemtary[i].getObject().value.trim().toMoney();
														}
														catch(err){}
													}
															
													eve.checkElemtByIndex(elt.getAttribute("elemtindex")); 
													
													eve.elemtary[i].afterOnBlur(); 
												}   //set event
				if(eve.elemtary[i].KEYUP_EVENT)
					elt.onkeyup  = function() {  eve.checkElemtByIndex(elt.getAttribute("elemtindex")); eve.elemtary[i].afterOnKeyup(); }  //set event
				
				
					
			}
			)(this,i);
		}	
	}
	this.add = function(obj)
	{
		
		this.elemtary.push(obj);
	}
	
	this.getElemtByID = function (eid)
	{	
		for(var i=0;i<this.elemtary.length ; i++)
		{
			if(eid == this.elemtary[i].elemtID)
				return i;
		}	
	}

	this.checkElemtByID = function(eid)
	{
		return this.checkElemtByIndex(this.getElemtByID(eid));
	}
	
	this.checkElemtByIndex = function(findex)
	{
		return this.checkElemt(this.elemtary[findex]);
	}
	
	this.getElementValue = function(elmt)
	{
			if( elmt.checkType == CheckType.Radio )
				return "";
			else
			if( elmt.checkType == CheckType.UBB )
			{
				try
				{
					eval("var s = "+elmt.elemtID +"_Editor.tGetContentWithoutUBB();");
					eval("var sor = "+elmt.elemtID +"_Editor.tGetUBB();");
					if(s != "")
						s = sor;
					return s;
				}
				catch (err)
				{
					return "";
				}
			}
			else
				return $(elmt.elemtID).value.trim(true) == "" ? "" : $(elmt.elemtID).value;
	}

	this.checkElemt = function (elmt)
	{
		//findex = findex - 1;
		//var elmt = this.elemtary[findex];
		if ( elmt.disabled )
		{
			return false;
		}
	
		var thisErr = false;
		var thisErrStr = "";
		var FieldStr = this.getElementValue(elmt);
		var showMaxLength ;
		var showMinLength ;
		var characters_tips = common_gbcharacters ;//= FieldStr.isContainGB() == true ? common_gbcharacters : common_characters ;
		
		
		showMaxLength = elmt.maxLength ; //showMaxLength:输出到页面
		showMinLength = elmt.minLength ;
		
		
		var matchMaxLength = elmt.maxLength ;  //matchMaxLength:长度匹配 
		var matchMinLength = elmt.minLength ;
		
		if(!elmt.checkGB && elmt.checkType != CheckType.Radio)
		{
			if(FieldStr.isContainGB())
			{
				matchMaxLength = matchMaxLength*2; //中文计算相应*2
				matchMinLength = matchMinLength*2;
			}
			else
			if(elmt.overStep)
				matchMaxLength = matchMaxLength*2;  //中文以长度*2来计算，所以最长值也相应*2,就算不包含中文也*2
		}
		if ( !elmt.ableEmpty || (FieldStr != "" && elmt.ableEmpty ))
		{
		
			var _checkLength = true; //default , check str length by checkType 
			
			switch( elmt.checkType )
			{
				case CheckType.No:
					// no
					break;

				case CheckType.Email:
					if ( !isEmail(FieldStr) )
					{
						thisErr = true;
					}
					break;

				case CheckType.Money:
					FieldStr = FieldStr.floatValue()+"";
					if ( !isMoney(FieldStr) || (!elmt.ableZero && (FieldStr*1) == 0)  ) //if can't equal 0 then throw err
					{		
						_checkLength = false;
						thisErr = true;
					}
					break;

				case CheckType.NumberOrLetter:
					if ( !isNumberOrLetter(FieldStr) )
					{
						thisErr = true;
					}
					break;

				case CheckType.Number:
					FieldStr = FieldStr.floatValue()+"";
					if ( !isNumber(FieldStr)|| (!elmt.ableZero && (FieldStr*1) == 0))
					{
						_checkLength = false;
						thisErr = true;
					}
					break;

				case CheckType.ChOrNumOrLetter:
					if ( !isChOrNumOrLetter(FieldStr) )
					{
						thisErr = true;
					}
					break;

				case CheckType.DateTime:
					if ( !isDateTime(FieldStr) )
					{	
						_checkLength = false;
						thisErr = true;
					}
					break;
				case CheckType.Float:
					FieldStr = FieldStr.floatValue()+"";
					if ( !isFloat(FieldStr) )
					{	
						_checkLength = false;
						thisErr = true;
					}
					break;
				case CheckType.Radio:
					 if(_getRadioValue(elmt.elemtID) == null)
					 {
						thisErr = true;
					 }
					 _checkLength = false;
					break;
				case CheckType.Password:
				
					 _checkLength = true;
					break;
				case CheckType.TelOrMobile:
					if ( !isTel(FieldStr) && !isMobil(FieldStr) )
					{
						thisErr = true;
					}
					break;
				case CheckType.Tel:
					if ( !isTel(FieldStr) )
					{
						thisErr = true;
					}
					break;
				case CheckType.PostCode:
					if ( !isPostalCode(FieldStr) )
					{
						thisErr = true;
					}
					break;
				case CheckType.BankAccount:
					if ( !isBankAccount(FieldStr) )
					{
						thisErr = true;
					}
					break;
			}
			thisErrStr = elmt.checkErrMessage;
			if(_checkLength)
			{
				var please_fill_tips_head = elmt.ableEmpty ? common_this_should_iffill : common_this_should_contain;
				
					if ( elmt.minLength==0 && elmt.maxLength==-1 )
					{
						thisErrStr = "";
					}
					else if ( elmt.minLength==0 && elmt.maxLength>0 )
					{
						if ( FieldStr.getLength() >matchMaxLength )
						{
							thisErrStr = please_fill_tips_head+common_up_to+" "+showMaxLength+" "+characters_tips;
							thisErr = true;
						}
					}
					else if ( elmt.minLength>0 && elmt.maxLength==-1 )
					{
						if ( FieldStr.getLength()<matchMinLength )
						{
							thisErrStr = please_fill_tips_head+common_at_least+" "+showMinLength+" "+characters_tips;
							thisErr = true;
						}
					}
					else
					{
						if ( FieldStr.getLength()<matchMinLength || FieldStr.getLength()>matchMaxLength )
						{
							thisErrStr = please_fill_tips_head;
							if ( elmt.minLength==elmt.maxLength )
							{
								thisErrStr += " "+showMinLength+" ";
							}
							else
							{
								thisErrStr += " "+showMinLength+"-"+showMaxLength+" ";
							}
							thisErrStr += characters_tips;
							thisErr=true;
						}
					}
		
			}
			
			if ( (FieldStr==null||FieldStr=="") && !elmt.ableEmpty && elmt.checkType != CheckType.Radio )
			{
				thisErrStr = elmt.emptyErrMessage;
				thisErr=true;
			}
			
		}
		if ( !elmt.extendCheck() && ( FieldStr != "" || elmt.checkType == CheckType.Radio ))
		{
				if( elmt.extendCheckErrMessage != null && thisErr != true)
					thisErrStr = elmt.extendCheckErrMessage;
				thisErr=true;
		}

		if ( thisErr )
		{
			this.isError = true;
			elmt.isError = true;
			try
			{
				if ( elmt.isCheckErrMessage )
				{
					$(elmt.errID).innerHTML = thisErrStr;
					$(elmt.errID).style.display = "";
					
					
					if(elmt.tipErrorClass != "")
					{
						$(elmt.errID).className = elmt.tipErrorClass;
					}
				}
			}
			catch (err)
			{
			}

			elmt.errorMsg = thisErrStr;

			//if(elmt.checkType != CheckType.Radio)
			//	$(elmt.elemtID).className = elmt.elemtErrClass ;
				
			return true;
		}
		else
		{
			elmt.clearError();
			return false;
		}
	}

	this.checkWholeForm = function ()
	{
		this.isError = false;
		for ( var i=0; i<this.elemtary.length ; i++ )  
		{
				//this.checkElemtByIndex(i) ;
				this.checkElemt(this.elemtary[i]);
		}
		/*
		try
		{
			for ( var i=0; i<this.elemtary.length ; i++ )  
			{
				if(this.elemtary[i].errorMsg == "")continue;

				$("checkMsgs").innerHTML += (i+1)+". "+this.elemtary[i].errorMsg+"<br/>";
			}
		}
		catch(err)
		{
		}
		*/
		this.gotoErrorElemt();
		return this.isError;
	}

	this.gotoErrorElemt = function()
	{
		for ( var i=0; i<this.elemtary.length ; i++ )  
		{
			var elmt = this.elemtary[i];
			if(elmt.isError == true && !elmt.disabled && elmt.checkType != CheckType.Radio)
			{
				try{
					if(elmt.checkType==CheckType.UBB){
						var y=GetAbsoluteLocationEx($(elmt.elemtID+"_container")).absoluteTop;
						window.scrollTo(0,y);
					}
				}catch(err){
					
				}
				try
				{
					elmt.getObject().focus();
					elmt.getObject().select();
					
				}catch(err)
				{
				
				}
				elmt.onCheckErrorFocus();
				break;
			}
		}
	}

	this.submit = function()
	{
		
	}
}

function _getRadioValue(rName)
{
	var rObj = document.getElementsByName(rName);
	for ( var i=0; i<rObj.length; i++ )
	{
		if ( rObj[i].checked )
		{
			return rObj[i].value;
		}
	}
	return null;
}
//----------------------------------------Echecker----------------------------------------------------------//


//---------------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------Area Beg-----------------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------------------------------------------------------------------------//

if(location_label==undefined){
	window.location_label = "洲";
}
if(country_label==undefined){
	window.country_label = "国家";
}
if(state_label==undefined){
	window.state_label = "省";
}
if(city_label==undefined){
	window.city_label = "城市";
}

if(common_pleasechoose==undefined){
	window.common_pleasechoose = "请选择";
}
//-------For old Area version-------------////
var _defaultObj_Area = null;
 function showAreaChoose(tdid,callbackEvent,initAreaAry,contryEvent,isDisplayLabel,isMyHome)
 {
 	_defaultObj_Area = new Area();
 	_defaultObj_Area.showAreaChoose(tdid,callbackEvent,initAreaAry,contryEvent,isDisplayLabel,isMyHome);
 }
  function showAreaChooseN(n,tdid,callbackEvent,initAreaAry,contryEvent,isDisplayLabel,isMyHome)
 {
 	var newobj = new Area(n);
 	newobj.showAreaChoose(tdid,callbackEvent,initAreaAry,contryEvent,isDisplayLabel,isMyHome);
 	return newobj;
 }
 
function countryFocus()
{
	_defaultObj_Area.countryFocus();
}

function setCityOnChange(fun)
{
	_defaultObj_Area.cityOnChange = fun;
}

function getAreaArrayVal ()
{
	return _defaultObj_Area.getAreaArrayVal();
}

function getAreaArrayTxt ()
{
	return _defaultObj_Area.getAreaArrayTxt();
}

function setAreaPleaseChoose()
{
	try
	{
 		_defaultObj_Area.setAreaPleaseChoose();
	}
	catch(err)
	{}
}

function checkArea()   
{
	return _defaultObj_Area.checkArea();
}

function setAreaFocusEvent(event)
{
	_defaultObj_Area.setFocusEvent( event );
}
//-------For old Area version End-------------////

function Area(aindex)
{
	this.index = aindex == null ? "" : aindex;  // empty String For old Area version
    var currentCountry=0;
	var currentState=0;  
	var currentCity=0;
	var oldCountry=0;
	var oldState=0;  
	var oldCity=0;
	var locationType =1;
    var allField=[];
 	var isInit = false;
    var firstAreaAry  = null;
  	var ContryOnChangeEvent = null;
    var ContryInitCallBackEvent = null;
	var hasAreaAry = false;
	var Selectid_country = "pre_locationList"+this.index;
	var Selectid_state = "pre_state"+this.index;
	var Selectid_city = "pre_city"+this.index;
	var Selectid_error = "locationErr"+this.index;
	this.FocusEvent = null;
	this._param = new Array();
	this.currentStateRecordCount = 0;
	this.currentStateRecordValue = 0;
    this.currentCityRecordCount = 0;

this.setFocusEvent = function(event)
{
	this.FocusEvent = event;
}

this.countryFocus = function()
{
	try
	{
		$(Selectid_country).focus();
		$(Selectid_country).select();
	}
	catch(err)
	{}

}

this.getAreaArrayVal = function()  //get values
{
	var areaval = new Array();
		areaval.push($(Selectid_country).value);
		areaval.push($(Selectid_state).value);
		areaval.push($(Selectid_city).value);
	return areaval;
}

this.getAreaArrayTxt = function()   //get texts
{
	var areaval = new Array();
		areaval.push($(Selectid_country).options[$(Selectid_country).selectedIndex].text);
		areaval.push($(Selectid_state).options[$(Selectid_state).selectedIndex].text);
		areaval.push($(Selectid_city).options[$(Selectid_city).selectedIndex].text);
	return areaval;
}

this.checkArea = function()   
{
	var areaval = this.getAreaArrayVal();
		if(areaval[2] == "0")
		{
			document.getElementById(Selectid_error).innerHTML = must_full_input;
			return false;
		}
		else
			document.getElementById(Selectid_error).innerHTML = "";
	return true;
		
}

this.setAreaPleaseChoose = function()
{
	try
	{

		this.showAreaChoose(this._param[0],this._param[1], this._param[2] , this._param[3] , this._param[4] , this._param[5]);
	}
	catch(err)
	{}
}


 
 this.showAreaChoose = function(tdid,callbackEvent,initAreaAry,contryEvent,isDisplayLabel,isMyHome)
 {
 	if(initAreaAry == null || initAreaAry ==undefined)
 	{
 		initAreaAry = null;
 	}
 	
 	var byMyDefaultLocal = initAreaAry == null;
 	if(initAreaAry != null)
 	{
 		byMyDefaultLocal = initAreaAry[0] == "0";
 	}
 	
 	this._param = new Array();
 	this._param.push(tdid);
 	this._param.push(callbackEvent);
 	this._param.push(initAreaAry);
 	this._param.push(contryEvent);
 	this._param.push(isDisplayLabel);
 	this._param.push(isMyHome);

 	this._toGetDefaultLocal(this._param , byMyDefaultLocal);

 }
 
this._toGetDefaultLocal = function(_param , byMyDefaultLocal)
{ 
	if(byMyDefaultLocal && hasLogin()) // notice: hasLogin() is external function
	 	sendRPC_getMyDefaultLocation(true , this); //callback use showAreaChoose
	else
	//if(_param[2] != null)
		this._showAreaChoose(_param[0],_param[1], _param[2] ,_param[3],_param[4],_param[5]);
}


this._showAreaChoose = function(tdid,callbackEvent,initAreaAry,contryEvent,isDisplayLabel,isMyHome)
{
	//init
	 currentCountry=0;
	 currentState=0;  
	 currentCity=0;
	 oldCountry=0;
	 oldState=0;  
	 oldCity=0;
	 locationType =2;
     allField=[];
 	 isInit = false;
     firstAreaAry  = null;
  	 ContryOnChangeEvent = null;
     ContryInitCallBackEvent = null;
     hasAreaAry = false;
     clearNode(tdid);
     
    //////////////////////////////////
    
	if(isDisplayLabel == null)
		isDisplayLabel = false;
	
	var firstlabe = "";
	if(isMyHome == null)
		firstlabe = country_label;
	else
	if(isMyHome)
		firstlabe = location_label;
	else
		firstlabe = country_label;	  
	
	ContryInitCallBackEvent = callbackEvent;
	
		
		var area1_panel = document.createElement("SPAN");
			area1_panel.id = Selectid_country+"_panel";
		
		var area2_panel = document.createElement("SPAN");
			area2_panel.id = Selectid_state+"_panel";
		
		var area3_panel = document.createElement("SPAN");
			area3_panel.id = Selectid_city+"_panel";

		var select_Loc = document.createElement("SELECT");
			select_Loc.name = Selectid_country;
			select_Loc.id = Selectid_country;
			select_Loc.size = 1;
		
		var select_State = document.createElement("SELECT");
			select_State.id = Selectid_state;
			select_State.size = 1;
		
		var select_City = document.createElement("SELECT");
			select_City.id = Selectid_city;
			select_City.size = 1;
		
		var select_Err = document.createElement("SPAN");
			select_Err.id = Selectid_error;
			select_Err.className = "errStyle";
		
		var space_span = document.createElement("SPAN");
			space_span.innerHTML = "";	
		
		var space_span2 = document.createElement("SPAN");
			space_span2.innerHTML = "";	
		
		var space_span3 = document.createElement("SPAN");
			space_span3.innerHTML = "";	
				
		var firstlabe_span = document.createElement("SPAN");
			firstlabe_span.id=Selectid_country+"_label";
			if(isDisplayLabel)
				firstlabe_span.innerHTML = firstlabe+" : ";	
		
		var statelabe_span = document.createElement("SPAN");
			statelabe_span.id=Selectid_state+"_label";
			if(isDisplayLabel)
				statelabe_span.innerHTML = ""+state_label+" : ";	
		
		var citylabe_span = document.createElement("SPAN");
			citylabe_span.id=Selectid_city+"_label";
			if(isDisplayLabel)
				citylabe_span.innerHTML = ""+city_label+" : ";			
				
		
		(
			function (areaObj , select_Loc , select_State , select_City)
			{
				select_Loc.onchange = function()
								  {
								  		areaObj.currentCountry=this.value;
								  		areaObj.getLocation(2,this.value );
								  		areaObj.countryOnChange();
								  }
				
				select_State.onchange = function()
								  {
								  		areaObj.currentState=this.value;
								  		areaObj.getLocation(3,this.value );
								  }
				
				select_City.onchange = function()
								  {
								  		areaObj.currentCity=this.value;
								  		areaObj.cityOnChange(this.value);
								  }
				/*
				if(areaObj.FocusEvent != null)
				{
					select_Loc.onfocus = function(){ alert("FFFF");areaObj.FocusEvent(); };
					select_State.onfocus = function(){ alert("FFFF");areaObj.FocusEvent(); };
					select_City.onfocus = function(){ alert("FFFF");areaObj.FocusEvent(); };
				}
				*/
			}
		)(this , select_Loc , select_State , select_City);	
	
		area1_panel.appendChild(firstlabe_span);
		area1_panel.appendChild(select_Loc);	
		area1_panel.appendChild(space_span3);	
		$(tdid).appendChild(area1_panel);
	  
		  area2_panel.appendChild(statelabe_span);
		  area2_panel.appendChild(select_State);
		  area2_panel.appendChild(space_span2);	
		  $(tdid).appendChild(area2_panel);

	  	
	  area3_panel.appendChild(citylabe_span);
	  area3_panel.appendChild(select_City);
	  $(tdid).appendChild(area3_panel);
	  
	  $(tdid).appendChild(space_span);
	  $(tdid).appendChild(select_Err);
  	

  		this.countryOnChange = function () {
  											try
  											{ 
  												contryEvent($(Selectid_country).value); 
  											}
  											catch(err)
  											{}
  											
  									  };
  	
  	var ltext=new Array();
	var lvalue=new Array();
	
	ltext.push(common_pleasechoose);
	lvalue.push("0");
	setSelectList(Selectid_country,ltext , lvalue); //set please choose
  	setSelectList(Selectid_country,bmh_country , bmh_country_ids);
	
	var isEmpytInitVal =false;

	if(initAreaAry != null)
		isEmpytInitVal = initAreaAry[0] != "0";
	
  	if(isEmpytInitVal)
  	{
  		hasAreaAry = true;
  		currentCountry = oldCountry = initAreaAry[0];
		currentState = oldState = initAreaAry[1];
		currentCity = oldCity = initAreaAry[2];
		
		setSelect(Selectid_country,currentCountry);
		this.countryOnChange();
		this.getLocation(2,currentCountry);
  	}
  	else
  	{
  		
  		setSelectList(Selectid_state,ltext , lvalue); //set please choose
  		setSelectList(Selectid_city,ltext , lvalue); //set please choose

  			try
  			{
  				
  				ContryInitCallBackEvent();
  			}
  			catch(err)
			{}
  	}
  	isInit = true;
  	
}

this.countryOnChange = function()
{
		
}

this.cityOnChange = function()
{
	
}

this.getLocation = function(n,lid){
	locationType=n;
	sendRPC_getLocation(lid , locationType ,this);
}


this.setLocationData = function(datas){

	var ltext=new Array();
	var lvalue=new Array();
	
	ltext.push(common_pleasechoose);
	lvalue.push("0");
	
	for(var n=0;n<datas.length;n++){
		
		ltext[ltext.length]=datas[n].locationStr;
		lvalue[lvalue.length]=datas[n].locationID;
	}
	
	if(locationType==1){
		removeAllOptions(Selectid_country);
		
		setSelectList(Selectid_country,ltext,lvalue);
		currentCountry=$(Selectid_country).value;
		if(currentCountry=="")currentCountry="0";
		if(isInit){
			this.getLocation(2,oldCountry);
		}
		
		
	}
	else if(locationType==2){
		
		removeAllOptions(Selectid_state);
		
		setSelectList(Selectid_state,ltext,lvalue);
		currentState=$(Selectid_state).value;
		if(currentState=="")currentState="0";

		this.currentStateRecordCount = datas.length;
		if(datas.length == 1)  
		{
				this.currentStateRecordValue = lvalue[1];
				oldState = lvalue[1];
				currentState = lvalue[1];
		}
		
		if(isInit)
		{
			this.getLocation(3,oldState);
		}
		else
		{
			this.getLocation(3,currentState);
		}
	}
	else if(locationType==3){
		removeAllOptions(Selectid_city);
		
		setSelectList(Selectid_city,ltext,lvalue);
		currentCity=$(Selectid_city).value;
		if(currentCity=="")currentCity="0";
		
		//this.currentCityRecordCount = datas.length;
		if(datas.length == 1)  
		{
				if(this.currentStateRecordCount == 1)
				{
					oldState = this.currentStateRecordValue;
					setSelect(Selectid_state,oldState);
				}
				oldCity = lvalue[1];
				setSelect(Selectid_city,lvalue[1]);
		}
		
		if(isInit)
		{
			setSelect(Selectid_state,oldState);
			setSelect(Selectid_city,oldCity);

			try
			{
				//if(hasAreaAry)this.countryOnChange();
				ContryInitCallBackEvent();
			}
			catch(err){}
			
			isInit = false;
		}
	}
   }

 }
 
 function clearNode(id) {
    var product=document.getElementById(id);
    while(product.childNodes.length>0) {
             product.removeChild(product.childNodes[0]);
     }
}

function sendRPC_getLocation(locationID , locationType ,areaObj){

		if(locationID==null)locationID=0;
		var rpcd = new RPCData();
          rpcd.reqData = "<Type>getLocation</Type><Label>";
          rpcd.reqData += "<LocalType>"+locationType+"</LocalType>";
          rpcd.reqData += "<LocationID>"+locationID+"</LocationID>";
	      rpcd.reqData += "</Label>";
	      rpcd.rpcPath = "PUBLIC_ACTION";
		  rpcd.rpcCallback = "getLocation_Callback(data)";
		  rpcd.vars.push(areaObj);
		 callRPC(rpcd);
 }
 
 function getLocation_Callback(data , rpcd){
 	
    var dataDOM = XMLTools.parseXML(data);	
	var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");	
	if ( authorized=="false" )
	{
		sessionTimeOutAction();	
	}
	else
	{

	   var success = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/success");
	   if(success == 'true')
	   {		
			var nodes = dataDOM.selectNodes("//RPCResponse/ResponseData/Label/List/locationDS");
			var datas = XMLTools.recordsFromXML(nodes);
			rpcd.vars[0].setLocationData(datas);	
	   }
	   else
	   {
	   		//var err = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label");
	   		//popwin().showMsg(err,"Error",0);
	   }
	} 
	
 }
 
 
 function sendRPC_getMyDefaultLocation(isBydefault , areaObj){
		if(isBydefault==null)isBydefault=true;
		var rpcd = new RPCData();
          rpcd.reqData = "<Type>getMyDefaultLocation</Type><Label>";
          rpcd.reqData += "<isByMyLocation>"+isBydefault+"</isByMyLocation>";
	      rpcd.reqData += "</Label>";
	      rpcd.rpcPath = "MEMBER_PREF_ACTION";
		  rpcd.rpcCallback = "getMyDefaultLocation_Callback(data)";
		  rpcd.vars.push(areaObj);
		 callRPC(rpcd);
 }
 
 function getMyDefaultLocation_Callback(data , rpcd){
    var dataDOM = XMLTools.parseXML(data);	
	var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");	
	if ( authorized=="false" )
	{
		sessionTimeOutAction();	
	}
	else
	{
	   var success = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/success");
	   if(success == 'true')
	   {			
			var country = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/country");
			var state = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/state");
			var city = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/city");
			
			var ary = new Array();
				ary.push(country);
				ary.push(state);
				ary.push(city);
			
			try
			{
					var _param = rpcd.vars[0]._param;
					rpcd.vars[0]._showAreaChoose(_param[0],_param[1], (_param[2] == null ? ary : null) ,_param[3],_param[4],_param[5]);
			}
			catch(err){}
	   }
	   else
	   {
	   		//var err = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label");
	   		//popwin().showMsg(err,"Error",0);
	   }
	} 
	
 }

//-----------------------------------------------------------------------Area   End----------------------------------------------------------------------------------//


////////////////////////////
////Tabs
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function Tabs()
	{
		this.styleID = "n";
		this.nowTab = "";
		this.needSelect = true;
		this.tabidsAry = new Array();
		this.tabvalsAry = new Array();
		this.classpre = "tab_";
		this.container;
		this.defaultTab = "";
		this.createTab = function (id,title,value,type,style,onClickEventStr)
		{
			if(style != null){
				this.styleID = style;
			}
			
			var _type = 0;
			
			if(type)
				_type = 1;
			
			if(value == null)
				value = "";
			
			if(onClickEventStr == null)
				onClickEventStr = "";
				
			this.tabidsAry.push(id);	
			this.tabvalsAry.push(value);
			
			var nid="tab_"+id;
			title=(getLength(title)>6)?title:"&nbsp;&nbsp;"+title+"&nbsp;&nbsp;";  //
			//document.write("<div id="+nid+" class='tab_all' ><input type=hidden id='"+id+"_clickTabEvent' value='"+onClickEventStr+"' /><input type='hidden' id='Val_"+id+"' value='"+value+"' /><div id="+id+"_1 class=\"tab_"+_type+"_1_"+this.styleID+"\"></div><div id="+id+"_2 class=\"tab_"+_type+"_2_"+this.styleID+"\"><span id='Title_"+id+"' >"+title+"</span></div><div id="+id+"_3 class=\"tab_"+_type+"_3_"+this.styleID+"\"></div></div>");
			var rstr="<div id="+nid+" class=\""+this.classpre+_type+"_all\"><input type=hidden id='"+id+"_clickTabEvent' value='"+onClickEventStr+"' /><input type='hidden' id='Val_"+id+"' value='"+value+"' /><div id="+id+"_1 class=\""+this.classpre+_type+"_left\"></div><div id="+id+"_2 class=\""+this.classpre+_type+"_center\"><span id='Title_"+id+"' >"+title+"</span></div><div id="+id+"_3 class=\""+this.classpre+_type+"_right\"></div></div>";
			if(this.container==undefined){
				document.write(rstr);
			}else{
				$(this.container).innerHTML += rstr;
			}

			
			
			if(type)
			{
				this.nowTab=id;
			}
		}
		this.initTab = function ()
		{
			for(var i=0;i<this.tabidsAry.length;i++)
			{
				(
					function(tab  ,id )
					{
						var nid="tab_"+id;
						$(nid).onclick = function ()
						{
							tab.clickTab(id);
							tab.changeTab();
						}
					}
				)
				(this , this.tabidsAry[i]);
			}
			
			if(this.defaultTab != "")
			{
				var nid = this.getIdByValue(this.defaultTab);
				this.changeTabCss(nid);
				this.nowTab = nid;
				this.changeTab();
			}
			
			this.init();
		}
		
		this.getIdByValue = function (val)
		{
			for(var i=0;i<this.tabvalsAry.length;i++)
			{
				if(this.tabvalsAry[i] == val)
				{
					return this.tabidsAry[i];
				}
			}
			
			return "";
		}
		
		this.getValue = function ()
		{
			try
			{
				return $("Val_"+this.nowTab).value;
			}
			catch(err)
			{
				return "";
			}
		}
		this.setValue = function (id,value)
		{
			try
			{
				$("Val_"+this.nowTab).value = value;
			}
			catch(err)
			{}
		}
		this.setTitle = function (id,title)
		{
			try
			{
				$("Title_"+id).innerHTML = title;
			}
			catch(err)
			{}
		}
		this.clickNowTab = function ()
		{
			this.click(this.nowTab);
		}
		this.click = function (id)
		{
			this.clickTab(id);
			this.changeTab();
		}
		this.changeTabCss = function (id)
		{
			if(this.nowTab != id)
			{
				try
				{
					document.getElementById(this.nowTab+"_1").className= this.classpre+"0_left"; //'tab_1_1_'+this.styleID;
					document.getElementById(this.nowTab+"_2").className= this.classpre+"0_center"; //'tab_1_2_'+this.styleID;
					document.getElementById(this.nowTab+"_3").className= this.classpre+"0_right"; //'tab_1_3_'+this.styleID;
				}catch(err)
				{}
				
				document.getElementById(id+"_1").className= this.classpre+"1_left";
				document.getElementById(id+"_2").className= this.classpre+"1_center";
				document.getElementById(id+"_3").className= this.classpre+"1_right";
			}
			else
			{
				if(!this.needSelect)
				{
					var selectVal = 1;
					if(document.getElementById(this.nowTab+"_1").className == 'tab_1_1_'+this.styleID) 
					{
						selectVal = 2; // change to selecting
					}
					
					try
					{
						document.getElementById(this.nowTab+"_1").className='tab_'+selectVal+'_1_'+this.styleID;
						document.getElementById(this.nowTab+"_2").className='tab_'+selectVal+'_2_'+this.styleID;
						document.getElementById(this.nowTab+"_3").className='tab_'+selectVal+'_3_'+this.styleID;
					}catch(err)
					{}
				
				}
			}
		}
		this.clickTab = function (id)
		{
			this.changeTabCss(id);
			this.nowTab = id ;
			
			var onClickEventStr = $(this.nowTab+"_clickTabEvent").value;
			try
			{
				if(onClickEventStr != "")
					eval(onClickEventStr);
			}
			catch(err){}	
			
			this.onclick();
		}
		this.changeTab = function ()
		{
			for(var i=0;i<this.tabidsAry.length;i++)
			{
				try
				{
					document.getElementById(this.tabidsAry[i]).style.display = this.tabidsAry[i] != this.nowTab ? "none" : "";
				}
				catch(err)
				{}
			}
		}
		
		this.init = function (){} // please override
		this.onclick = function (){} // please override
		
	}

//------------------------------------------Tabs ------------------------------------------//
	
////////////////////////////
////CheckBoxes
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	function CheckBoxes(_id , _objname)
	{
		this.ID = _id;
		this.name = _id;
		this.valary = new Array();
		this.newObjName = _objname;
		this.selectAll = function ()
						{
							this.setAllSelectCheck(true);
						}
		this.diselectAll = function ()
						{
							this.setAllSelectCheck(false);
						}
		this.switchEach = function ()
						{
							this.setAllSelectCheck(false,true);
						}
		this.setAllSelectCheck = function (_val,_isSwitch)
							  {
							  	if(_isSwitch == null)
							  		_isSwitch = false;
							  	var objs = document.getElementsByName(this.name);
							  
								for ( var i=0; i<objs.length; i++ )
								{
									if(_isSwitch)
										objs[i].checked = !objs[i].checked;
									else
										objs[i].checked = _val;
								}
								
								this.onChange();
							  }
		this.getAryAttribute = function (attributeName , isNeedChecked)
							{
								return this.getAryValue(attributeName , isNeedChecked);
							}
		this.getAryValue = function (attributeName , isNeedChecked)
							{
								if(isNeedChecked == null)isNeedChecked = true;
								if(attributeName == null)attributeName = "value";
								var tmp = new Array();
								var objs = document.getElementsByName(this.name);
								for ( var i=0; i<objs.length; i++ )
								{
									if(!isNeedChecked || (objs[i].checked && isNeedChecked))
									{
										tmp.push(objs[i].getAttribute(attributeName));
									}
								}
								return tmp;
							}
		this.getValueStr = function ()
							{	
								var val = "";
								var tmp = this.getAryValue();
								for ( var i=0; i<tmp.length; i++ )
								{
									val += tmp[i]+",";
								}
								if(val.length>0)
									val = val.substring(0,val.length-1);
								return val;
							}
		this.onChange = function()  //please override
						{
							//do something
						}
		this.singleOnChange	= function ()
							{
								var objs = document.getElementsByName(this.name);
								for ( var i=0; i<objs.length; i++ )
								{
									(
										function (obj , cbObj)
										{
											obj.onclick = function(){cbObj.onChange();};
										}
									)(objs[i] , this);
								}
							}				
	}
//------------------------------------------CheckBoxes ------------------------------------------//



////////////////////////////////////////////////////////////////////////////////////
///           Popup  Move Object     ###By James	   
/////////////////////////////////////////////////////////////////////////

function Mover(id)
{ 
	this.moveObjID = id ;
	this.canMove = true;
	this.POS_X = -1;
	this.POS_Y = -1;
	this.oldMouseMoveEVENT = document.onmousemove;
	this.oldMouseUPEVENT = document.onmouseup;
     /////////////----------------------------------------------------------------------------
     
     this.Move=function(Evt,T) 
		{
			if(!this.canMove) return ;
		   
		   if(this.moveObjID=="") return; 
		   
		   var o = $(this.moveObjID); 
		   
		   if(!o) return;
		   evt = Evt ? Evt : window.event; 
		   o.style.position = "absolute";
		   //o.style.zIndex = 603000;
		   var obj = evt.srcElement ? evt.srcElement : evt.target; 
		
		   	 var w = document.body.clientWidth;
		     var h = document.body.clientHeight;
		     var l = 0; 
		     var t = 0;
		     var div = document.createElement("DIV");
		   
		     div.style.cssText = "filter:alpha(Opacity=10,style=0);Opacity:0.0;width:"+w+"px;height:"+h+"px;top:"+t+"px;left:"+l+"px;position:absolute;background:#FFFFF";
		     div.setAttribute("id", this.moveObjID +"temp");
		     div.style.zIndex = o.style.zIndex + 5;
		     
		     document.body.appendChild(div);
		     
		    this.Move_OnlyMove(this.moveObjID,evt,T); 
		} 
		 
	
		this.Move_OnlyMove = function(Id,Evt,T) 
		{
		   var o = $(this.moveObjID); //$(Id+"temp"); 
		   
		   var tempo = $(Id+"temp");
		   
		   if(!o) return; 
		   
		   evt = Evt?Evt:window.event;
		   
		   var relLeft = evt.clientX - o.offsetLeft;
		   var relTop = evt.clientY - o.offsetTop;

			
		   if(o.setCapture)
		   {
		     o.setCapture();
		   } 
		   else
		   if(window.captureEvents)
		   { 
		     window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP); 
		   } 
		  
		 (
			   	function (obj , o ,tempo)
			   	{
					   document.onmousemove = function(e) 
					   { 
					      if (!o) return; 
					    	
					      e = e ? e : window.event; 
					      
					      if (e.clientX - relLeft <= 0) 
					       o.style.left = 0 +"px"; 
					      else 
					      if (e.clientX - relLeft >= document.body.clientWidth - o.offsetWidth - 2) 
					       o.style.left = (document.body.clientWidth - o.offsetWidth - 2) +"px"; 
					      else 
					       o.style.left = e.clientX - relLeft +"px"; 
					       
					      if (e.clientY - relTop <= 1) 
					       o.style.top = 1 +"px"; 
					      else 
					      if (e.clientY - relTop >= document.body.clientHeight - o.offsetHeight - 30) 
					       o.style.top = (document.body.clientHeight - o.offsetHeight - 30) +"px"; 
					      else 
					       o.style.top = e.clientY - relTop +"px"; 
					      
					      //document.title = "X: "+o.style.left +"    Y: "+ o.style.top;
					      //obj.POS_X = o.style.left.substring(0,o.style.left.length-2);
				  	   	  //obj.POS_Y = o.style.top.substring(0,o.style.top.length-2);
					   } 
			   		
					     document.onmouseup = function() 
					     { 
					      if (!o) return;
				  	   	  
					      if (!window.captureEvents) 
					      	o.releaseCapture();  
					      else 
					      	window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP); 
					      	
					      document.body.removeChild(tempo); 
					      tempo = null; 
					      
					      document.onmousemove = obj.oldMouseMoveEVENT;
				  	   	  document.onmouseup = obj.oldMouseUPEVENT;
					     }  
				  }
		     )(this , o ,tempo);
		} 
} 

var popup_title_failed = "失败";
var popup_title_succeed = "成功";
var popup_title_warning = "警告";
var popup_title_alert = "提示";
var popup_title_question = "询问";
//var popup_btn_ok = "确定";  // defined in JSvariable.jsp


var viewerPage = new Viewer("viewerPage") // parameter is the same obj name
 viewerPage.show_slowly =false;     //set pop-up window slowly , default is false
 //viewerPage.hide_slowly =true;

var popupPage =new  Popup("popupPage" , viewerPage , 2) ;   // parameter is the same obj name,  popup object must be created after viewer and mover 

//  for example
//	popup.popupPage("a.html","Title","callback" )

//function callback (){     
//					  var pdata = popup.getXMLData();   // get the xmldata
//					  alert( pdata.A ); 
//			}


	viewerPage.hiddened = function () // do something after hidden 
	{
		popupPage.hideCoverDiv() ;			  // hide the background 
		popupPage.innerIFRAMELoaded();       // if no close loading image ,close the loading image
		//popupPage.innerIFRAMEResizeDefault();
		popupPage.innerIFRAMEMoveCenter();   // move to center (initialize position)
	}

//viewer.showed = function () // do something after showed , please override
//{
	
//}



//////////////////////
/////          defined popup message
///////////////////////////////////////////////


var viewerMsg = new Viewer("viewerMsg") // parameter is the same obj name
 viewerMsg.show_slowly =true;     //set pop-up window slowly , default is false
 //viewerMsg.hide_slowly =true;
 
var popupMsg =new  Popup("popupMsg" , viewerMsg , 1) ;   // parameter is the same obj name,  popup object must be created after viewer and mover 


	viewerMsg.hiddened = function () // do something after hidden 
	{
		popupMsg.hideCoverDiv() ;			  // hide the background 
		//popupMsg.innerIFRAMELoaded();       // if no close loading image ,close the loading image
		popupMsg.innerIFRAMEResizeDefault();
		popupMsg.innerIFRAMEMoveCenter();   // move to center (initialize position)
	}



//////////////////////////
/////////////Dialog
////////////////////////////////////
var viewerDialog = new Viewer("viewerDialog") // parameter is the same obj name
  viewerDialog.show_slowly =true;     //set pop-up window slowly , default is false
  //viewerDialog.hide_slowly =true;
  
var popupDialog =new  Popup("popupDialog" , viewerDialog , 3) ;   // parameter is the same obj name,  popup object must be created after viewer and mover 


	viewerDialog.hiddened = function () // do something after hidden 
	{
		popupDialog.hideCoverDiv() ;			  // hide the background 
		//popupDialog.innerIFRAMELoaded();       // if no close loading image ,close the loading image
		popupDialog.innerIFRAMEResizeDefault();
		popupDialog.innerIFRAMEMoveCenter();   // move to center (initialize position)
	}



var popuper = new Popuper(popupPage , popupMsg ,popupDialog);  // defined popuper , use this object to opera popup


var idAry = new Array();
	//idAry.push(popupPage.popupID);
	idAry.push(popupMsg.popupID);
	idAry.push(popupDialog.popupID);
popupSetScroll(idAry);


//window_onresize( "popupPage.refreshCoverDiv()" );

////////////////////////////////////////////////////////////////////////////////////
///           Popup  Move Object     ###By James	   2008-2-2
/////////////////////////////////////////////////////////////////////////

function Popuper (pPage,pMsg,pDialog)
{
	this.Page = pPage;
	this.Msg = pMsg;
	this.Dialog = pDialog;
	this.DialogOneOffSlowly = false;
	this.zindex = 503000;
	
	this.Page.UIIndex = this.zindex;
	this.zindex+=1000;
	this.Dialog.UIIndex = this.zindex;
	this.zindex+=1000;
	this.Msg.UIIndex = this.zindex;
	
	this.Page.initPopup();				 // Initialize after set UIIndex
	this.Msg.initPopup();				 // Initialize 
	this.Dialog.initPopup();				 // Initialize 
	
	this.tmpdata = new Array();
	
	
	this.showPage = function (contentVar,titleVar,callback,closeCallback,XCloseCallback,widthVar,heightVar)
	{
		if(callback == null)
			callback = "";

		this.Page.popupPage(contentVar,titleVar,callback,closeCallback,XCloseCallback,widthVar,heightVar);

	}
	
	this.showMsg = function (contentVar,titleVar,callback,otherpara, buttonLabel , XCloseCallback,widthVar,heightVar)
	{
		if(callback == null)
			callback = "";
							
			this.Msg.popupMsg(contentVar,titleVar,callback,otherpara,buttonLabel,XCloseCallback,widthVar,heightVar);
	}
	
	this.showDialog = function (contentVar,titleVar,buttonVar,methodVar,closeCallback,msglevel,XCloseCallback,widthVar,heightVar)
	{
		this.Dialog.ParentID = this.Page.popupID;
		this.Dialog.popupDialog(contentVar,titleVar,buttonVar,methodVar,closeCallback,msglevel,XCloseCallback,widthVar,heightVar);

		if(this.DialogOneOffSlowly)
		{
			if(this.Dialog.viewer.show_slowly)
				this.setDialogShowSlowly(false);
			else;
				this.setDialogShowSlowly(true);
				
			this.DialogOneOffSlowly = false;
		}
	}
	this.setDialogShowSlowly = function (tof) // set one-off
	{
		this.DialogOneOffSlowly = true;
		
		if(tof)
			this.Dialog.viewer.show_slowly = true;
		else
			this.Dialog.viewer.show_slowly = false;
	}
	
	this.closePage = function(tf)
	{
		this.Page.closePopup(tf);
	}
	this.closeDialog = function (tf)
	{
		this.PARENT_POPUPER.Dialog.closePopup(tf);
	}
	this.ActiveCloseCallback = function ()
	{
		this.Page.isExeCloseCallback = true;  // in showPage() , this attribute's value is default false
	}
	this.getTempXMLData = function ()
	{
		return this.Page.getTempXMLData();
	}
	this.setTempXMLDataByObj = function (obj) //replace data
	{
		this.Page.TEMP_XMLDATA = obj;
	}
	this.setTempXMLData = function (xml)
	{
		this.Page.setTempXMLData(xml);
	}
	this.showed = function ()
	{
	}
	this.getTempDataList = function ()
	{
		return this.Page.TEMP_DATALIST;
	}
	this.setTempDataList = function (data)
	{
		this.Page.TEMP_DATALIST.add(data);
	}
	this.addTempDataList = function (data,idx)
	{
		if(idx == null)
			this.Page.TEMP_DATALIST.add(data);
		else
		{
			try
			{
				this.Page.TEMP_DATALIST[idx] = null;
				this.Page.TEMP_DATALIST[idx] = data;
			}
			catch(err)
			{
				//alert("Popuper.addTempDataList() : no such index");
			}
		}
			
	}
	
	this.LockPage = function()
	{
		this.Page.isLOCKING = true;
	}
	this.ReleasePage = function()
	{
		this.Page.isLOCKING = false;
	}
	
	this.showLoading = function(isCover)
	{	
		this.Page.innerIFRAMELoading(isCover);
	}
	this.hideLoading = function(isCover)
	{	
		this.Page.innerIFRAMELoaded(isCover);
	}
	this.getCallBackXMLData = function()
	{	
		return this.Page.getCallBackXMLData();
	}
	this.getTempData = function(idx)
	{
		return this.tmpdata[idx];
	}
	this.setTempData = function(idx , val)
	{
		this.tmpdata[idx] = val;
	}
}



////////////////////////////////////////////////////////////////////////////////////
///           Popup Object     ###By James	   2008-1-22
/////////////////////////////////////////////////////////////////////////
function  Popup (pid,viewer,type)  
{
						this.popupID = pid ;
						this.autoSize = true ;
						this.width = 260 ;  //default
						this.height = 100;	//default
						this.Towidth = 0;	
						this.Toheight = 0;
						this.title =  "";
						this.isOpen = false;
						if(staticServer==undefined || staticServer ==null){
							staticServer = "//static.bangyibang.com/byb";
						}
						this.APP_ROOTPATH = staticServer;
						this.IMGPATH = this.APP_ROOTPATH+"/images/";
						this.LOADING_NAME = (window.location+"").indexOf("/pingten")>-1?"loading_pingten":"loading";
						this.LOADING_IMGPATH = this.IMGPATH + this.LOADING_NAME +".gif?v=201007121651" ;
						this.DIALOG_PATH = this.IMGPATH + "dialog/" ;
						this.IFRAME_CALLBACK_XMLDATA = null ;
						this.TEMP_XMLDATA ;
						this.TYPE ;
						this.MSG = 1;
						this.PAGE = 2;
						this.DIALOG = 3;
						//this.XmlDataKey = "";   // separator  , get xmldata by this key 
						this.CallBackEVENT = "";
						this.CloseCallBackEVENT = "";
						this.viewer = viewer ;
						this.mover ;
						this.CURRENT_PAGESRC = "";
						this.isPageLoading = false ;
						this.LOADING_TIMEOUT = 8000 ; // 8 seconds
						this.tempCloseEVENT ;
						this.isChildEVENT = false;
						this.ParentID = "" ; 
						this.isExeCloseCallback = false; //if true then execute closeCallback event , false not
						this.TEMP_DATALIST = new Array();
						this.LoadingIMGObj = null;
						this.IFRameObj = null;
						this.SnapUserID = null;
						this.XCloseCallback = null;
						this.EventHead = "";
						this.UIIndex = 0;
						this.isLOCKING = false;
						this.BeforeXCloseEvent = null;   //son page used
						this.loadingStack = new Array();
						this.initPopup = function ()
						{
								//this.popupID = cid
								
								this.mover = new  Mover(this.popupID);  // parameter is be moved obj name
								this.mover.canMove =true; //set the window can move  , default is true
								
								this.TYPE = type;
								this.createPageStyleElement(this.popupID);
								
								this.tempCloseEVENT = this.closePopup ;
						}
						this.getPositionAry = function ()
						{
							var x = $(this.popupID).style.left.substring(0,$(this.popupID).style.left.length-2); 
							var y = $(this.popupID).style.top.substring(0,$(this.popupID).style.top.length-2);
						
							var a = new Array();
							a.push(x*1);
							a.push(y*1);
							return a;
						}
						this.innerIFRAMEResizeDefault = function ()  
						{
							this.innerIFRAMEResize(this.width,this.height);
						}
						this.innerIFRAMEResize = function (w,h)  // use by iframe context
						{
							
							if(w != null && h != null)
							{
								//if(!this.autoSize)
								//{
								//	w = this.Towidth  ;
								//	h = this.Toheight ;
								
								//}
							}
							else
							{
									w = this.width  ;
									h = this.height ;
							}
							
							
							
							if($(this.popupID+"_ifr") != null)   // not popupMsg resize iframe 
							{
								$(this.popupID+"_ifr").style.height = h  +"px";
								$(this.popupID+"_ifr").style.width  = w  +"px";
							}
								
							try
							{
								$(this.popupID+"_top_center").style.width = (w*1 - 24)+20 +"px"; //  +20 : 2 * 10 padding(left ,right)
								$(this.popupID+"_toppanel").style.width = w+10+20 +"px";  // +10 : 2 * 5px border , +20 : 2 * 10 padding(left ,right)
								$(this.popupID+"_bottompanel").style.width = w+10+20 +"px"; // +10 : 2 * 5px border , +20 : 2 * 10 padding(left ,right)
								$(this.popupID+"_contentpanel_left").style.height = h+10 +"px";
								$(this.popupID+"_contentpanel_right").style.height = h+10 +"px";
							}
							catch(err){}
								
								
								
								
								$(this.popupID+"_content").style.height = h +"px";
								$(this.popupID+"_content").style.width = w +"px";

								$(this.popupID+"_inner").style.height = h +90+"px";
								$(this.popupID+"_inner").style.width = w +40+"px";
								
								$(this.popupID).style.height=h +85 +"px";
								$(this.popupID).style.width= w +45+"px";

						}
						
						this.innerIFRAMEMoveCenter = function (offsetLeft,offsetTop)
						{
							if(offsetLeft == null )
								offsetLeft = 0 ;
							if(offsetTop == null)
								offsetTop = 0;
						
								
							var lpostep = 0 + offsetLeft;
							var tpostep = 0 + offsetTop;
							if(this.TYPE == this.MSG || this.TYPE == this.DIALOG)
							{
								lpostep = 0
								//tpostep = 100
							}
						
							var hh =$(this.popupID).style.height.substring(0,$(this.popupID).style.height.length-2);
							
							var t=getBodyObj().scrollTop + (getBodyObj().clientHeight- $(this.popupID).style.height.substring(0,$(this.popupID).style.height.length-2))/2 -tpostep;
							var l=getBodyObj().scrollLeft + (getBodyObj().clientWidth- $(this.popupID).style.width.substring(0,$(this.popupID).style.width.length-2))/2 -lpostep;	
							this.innerIFRAMEMove(t,l);
							
						}
						
						this.innerIFRAMEMove = function (t,l)
						{
							if(t < 0 )
								t = 10;
							if(l <0 )
								l = 10;
							$(this.popupID).style.top = t +"px";
							$(this.popupID).style.left = l +"px";
						}
						this.innerIFRAMELoading = function (isCover)
						{
								var t=(getBodyObj().scrollTop + (getBodyObj().clientHeight)/2 - 100) + "px";
								var l=(getBodyObj().scrollLeft + (getBodyObj().clientWidth)/2 -100) + "px";
								
								if(isCover == null)
									isCover = false;
								if(isCover)
								{
									this.showCoverDiv();
								}
							
								if(t < 0 )
									t = 10;
								if(l <0 )
									l = 10;
								try
								{
									
									$(this.popupID+"loader").style.left = l ;
									$(this.popupID+"loader").style.top = t ;
									$(this.popupID+"loader").style.display ="";
									this.isPageLoading = true;
									this.loadingStack.push(true);
								}
								catch(err)
								{}
						}
			
						this.innerIFRAMELoaded = function (isCover)   //  finished load ,then close loading image
						{
							this.loadingStack.pop();

							if(this.loadingStack.length >0) return ;
							
							try
							{
								
								if(isCover == null)
									isCover = false;
									
								if(isCover)
									this.hideCoverDiv();
								
								$(this.popupID+"loader").style.display ="none";
								this.isPageLoading = false ;
							}
							catch(err)
							{}
							
							try
							{
								$(this.popupID+"_pageloading").style.display = "none";
							}
							catch(err){}
							
							try
							{
								$(this.popupID+"_content").removeChild(this.LoadingIMGObj);
							}
							catch(err){}
						}
						
						this.popupTimeout = function ()
						{
							this.innerIFRAMELoaded()
							this.isPageLoading = false ;
						}
						this.popupPage = function(pageVar,titleVar,callback,closeCallback,XCloseCallback,widthVar,heightVar)  // pop-up the page , pageVar is page URL
						{
							this.showCoverDiv();
							
							this.isExeCloseCallback = false;
							this.CallBackEVENT = callback ;
							this.CloseCallBackEVENT = closeCallback ;
							this.XCloseCallback = XCloseCallback;
							this.isOpen =true ;
							
							if(titleVar == "" || titleVar == null)
									titleVar =this.title;

							if(widthVar != null && heightVar != null)
							{
										this.Towidth = widthVar;
										this.Toheight =  heightVar;
							}
							
							
							
							
							/*
							if( this.CURRENT_PAGESRC != pageVar )   // if no opened always , then load page
							{
							*/
								this.innerIFRAMEResize(300,80);
								this.IFRAME = "<iframe name='"+this.popupID+"_ifr"+new Date()+"' id='"+this.popupID+"_ifr'   frameborder=0 border=0  src='"+staticServer+"/blank.html' scrolling='no' style='height:0px;margin:0px;padding:0px;'>";
								  this.IFRAME += "</iframe>";
								  this.IFRAME += "<img src='"+WebRoot+"/images/loading.gif?v=201007121651' border='0' id='"+this.popupID+"_pageloading' >";
								  this.IFRAME += "</img>";
								  $(this.popupID+"_content").innerHTML = this.IFRAME;
								  $(this.popupID+"_ifr").src=pageVar;
								this.innerIFRAMEMoveCenter();   // move to center 	  
								
								//$(this.popupID+"_title").innerHTML="<span style='color:#CF5503;'>"+titleVar+"</span>";  
							/*
							}
							else
							{
								this.viewer.showed = function()
								{
										try
										{
											eval(popuper.Page.popupID+"_ifr.popupPage.onload()")
										}
										catch(err){}
								}
							}
							*/
							
							this.CURRENT_PAGESRC = pageVar
							this.viewer.show(this.popupID);   
							
						
						}
						this.popupMsg = function(contentVar,titleVar,callback,msglevel,buttonLabel,XCloseCallback,widthVar,heightVar)  // pop-up the common message
						{
							/*
							msglevel
							0. logic error
							1. logic right
							2. common mark
							3. question mark
							4. system error
							*/
							this.showCoverDiv();
							this.CallBackEVENT = callback ;
							this.XCloseCallback = XCloseCallback;
							this.isOpen =true ;
							
							if(msglevel == null) msglevel = 2 ;
							
							if(titleVar == "" || titleVar == null)
							{
									titleVar = this.title;
									
									try
									{
										switch(msglevel)
										{
											case 0 :
												titleVar = popup_title_failed
												break;
											case 1 :
												titleVar = popup_title_succeed
												break;
											case 2 :
												titleVar = popup_title_alert
												break;
											case 3 :
												titleVar = popup_title_question
												break;
											case 4 :
												titleVar = popup_title_error
												break;
										}
										
										
									}catch(err){ }
							}
									
							var htmlAry = new Array();
								htmlAry.push("<table style='width:100%;' align='center'>");
								htmlAry.push("<tr>");
								
									htmlAry.push("<td valign='center' width='60px' align='center'>");
										htmlAry.push("<img src='" +this.DIALOG_PATH + msglevel +".gif?v=201007121651' />");	
									htmlAry.push("</td>");
									
									htmlAry.push("<td style='' align='left'>");
										htmlAry.push("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+contentVar);	
									htmlAry.push("</td>");
									
								htmlAry.push("</tr>");
								 
								htmlAry.push("<tr>");
									htmlAry.push("<td>");
										htmlAry.push("&nbsp;");
									htmlAry.push("</td>");
									htmlAry.push("<td style='height:30px;padding-top:5px;text-align:left;'>");
										htmlAry.push("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<div class='button_gray' onclick=\""+this.popupID+".closePopup()\">"+( (buttonLabel == null || buttonLabel ==  "")? popup_btn_ok : buttonLabel)+"</div>");
									htmlAry.push("</td>");
								htmlAry.push("</tr>");
								
								htmlAry.push("</table>");
								
							
							$(this.popupID+"_content").innerHTML=htmlAry.join('');
							//$(this.popupID+"_title").innerHTML=titleVar;
							/*
							if(widthVar != null && heightVar != null)
							{
										this.Towidth = widthVar;
										this.Toheight =  heightVar;
										if(this.autoSize)
										{
											widthVar = this.width;
											heightVar = this.height;
										}
							}
							*/							
							this.innerIFRAMEResize(widthVar,heightVar);

							this.innerIFRAMEMoveCenter();

							this.viewer.show(this.popupID);
						}
						
						this.popupDialog = function(contentVar,titleVar,buttonVar,methodVar,closeCallback,msglevel,XCloseCallback,widthVar,heightVar)
						{
							/*
							msglevel
							0. logic error
							1. logic right
							2. common mark
							3. question mark
							4. system error
							*/
							this.showCoverDiv();
								
							this.isOpen =true ;
							if(titleVar == "" || titleVar == null)
									titleVar = popup_title_question; //this.title;
							if(msglevel == null) msglevel = 3 ;
							   
							this.CallBackEVENT = closeCallback ;
							this.XCloseCallback = XCloseCallback;
							
							var dialog_bt="";
							var dialog_buttons=buttonVar.split("|");
							var dialog_methods=methodVar.split("|");

							for(var i=0;i<dialog_buttons.length;i++){
								var clkevent = "";
								if(dialog_methods[i] == undefined)
									clkevent = this.popupID+".closePopup()";
								else
									clkevent = this.popupID+".dialogBtnEevent(\""+Trim(dialog_methods[i])+"\")" ;
								var style="";
								if(i == 0){
									//style += "padding-left:80px;";
								}else{
									style += "margin-left:10px;";
								}
								//dialog_bt+="<input type=\"button\" value=\""+dialog_buttons[i]+"\" onclick="+clkevent+" style=\"padding:0px 5px;\">&nbsp;";
								dialog_bt += "<div class='button_gray' style=\""+style+"\" onclick="+clkevent+">"+dialog_buttons[i]+"</div>";
							}

								
								var htmlAry = new Array();
								htmlAry.push("<table style='width:100%;' align='center'>");
								htmlAry.push("<tr>");
								
									htmlAry.push("<td valign='center' style='width:60px;' align='center'>");
										htmlAry.push("<img src='" +this.DIALOG_PATH + msglevel +".gif?v=201007121651' />");	
									htmlAry.push("</td>");
									
									htmlAry.push("<td  align='left'>");
										htmlAry.push("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+contentVar);	
									htmlAry.push("</td>");
									
								htmlAry.push("</tr>");  
								 
								htmlAry.push("<tr>");
									htmlAry.push("<td>");
										htmlAry.push("&nbsp;");
									htmlAry.push("</td>");
									htmlAry.push("<td style='height:30px;padding-top:5px;text-align:left;'>");
										htmlAry.push("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+dialog_bt);
										htmlAry.push("<div style='clear:both;'></div>");
									htmlAry.push("</td>");
								htmlAry.push("</tr>");
								
								htmlAry.push("</table>");
												
							$(this.popupID+"_content").innerHTML=htmlAry.join('');

							//$(this.popupID+"_title").innerHTML=titleVar;

					
							//if(widthVar != null && heightVar != null)
							//{
										//this.Towidth = widthVar;
										//this.Toheight =  heightVar;
										//if(this.autoSize)
										//{
										//	widthVar = this.width;
										//	heightVar = this.height;
										//}
							//}
							this.innerIFRAMEResize(widthVar,heightVar);

							this.innerIFRAMEMoveCenter();
							
							//$(this.popupID).style.display="";
							this.viewer.show(this.popupID);
							
							//$(this.popupID+"_inner_button").focus();
						}
						this.refreshCoverDiv = function()
						{
								if(!this.isOpen)return ;

									this.showCoverDiv();
									if($(this.popupID).style.left.substring(0,$(this.popupID).style.left.length-2) < 0)
											$(this.popupID).style.left = 5 +"px";
									if($(this.popupID).style.top.substring(0,$(this.popupID).style.top.length-2) < 0)
											$(this.popupID).style.top = 5 +"px";
						}
						this.showCoverDiv = function(){
							try
							{
								var nowHeight=getBodyObj().scrollHeight;
	
								$(this.popupID+"coverDiv").style.height=(nowHeight*1)+"px";
								$(this.popupID+"coverFrame").style.height=(nowHeight*1)+"px";
								
								var nowWidth=getBodyObj().scrollWidth;
							
								$(this.popupID+"coverDiv").style.width=(nowWidth*1)+"px";
								$(this.popupID+"coverFrame").style.width=(nowWidth*1)+"px";
								
								$(this.popupID+"coverDiv").style.display="";
							}
							catch(err)
							{}
						}
			
						this.checkCloseEVENT = function()
						{
							return true;
						}
						this.closePopup = function(tf)
						{

							if(tf == null)tf = 1;
							try
							{
								//$(this.popupID+"_ifr").src = ""
							}
							catch (err){}
							if(!this.isPageLoading)   
							{
								this.viewer.hidden(this.popupID);
							 
							//$(this.popupID).style.display="none";
								
							}
							
							this.isOpen = false ;
							
							this.hideCoverDiv();
							this.closedEvent();
							try
							{
								if( (this.TYPE == this.MSG || this.TYPE == this.DIALOG) && tf == 1 )   //msg clcick ok callback , 
								{
									this.exeEevent( this.CallBackEVENT );
								}
								else
								if(this.TYPE == this.PAGE && tf == 1 && this.isExeCloseCallback)   //page clcick X callback , tf == 1 is natural close ,else not execute callbackevent
								{
									this.exeEevent( this.CloseCallBackEVENT );
								}
							}
							catch(err)
							{
							}
							
							
							this.IFRAME_CALLBACK_XMLDATA = null;
							this.TEMP_XMLDATA = null;
							this.TEMP_DATALIST = new Array();
						}
						this.closedEvent = function () // please overidde
						{
							return;
						}
						this.dialogBtnEevent = function (eventstr,tf)
						{
							var mtf = eventstr.split(":");  // successEvent:true , true:exe closepopup , false :else
							var isExeClose = mtf.length > 1 ? mtf[1] : "true";
							
							this.exeEevent(mtf[0]);
							if(isExeClose == true || isExeClose == "true")
									this.closePopup(0);
						}
						this.exeEevent = function(eventstr)
						{
							if(eventstr == "" || eventstr == undefined)return ;
									var te = "";
									
									
										if(this.isChildEVENT)
										{
											
											if(this.ParentID == "")return ;  //dialog in snap ,parentid is "";
											if(this.SnapUserID == null)
												te = "$('"+this.ParentID+"_ifr').contentWindow.";  //firefox must use .contentWindow
											else
												te = "$('"+this.SnapUserID+"_ifr').contentWindow.";
												
											this.SnapUserID = null ;
											this.isChildEVENT = false ;
										}
								
									var es = eventstr.split(";");
									for(var i=0;i<es.length;i++)
									{	
										var lf = "()";
										try
										{
											if( es[i].indexOf("()") > 0 || es[i].indexOf("(") > 0 || es[i].indexOf(")") > 0)
												lf = "";
												
											eval(te + es[i] + lf);
										}
										catch(err)
										{
										}
									}
							
						}
						this.hideCoverDiv = function()
						{    
							try
							{
									$(this.popupID+"coverDiv").style.display="none";    //  inside use
							}
							catch(err)
							{}
						}

						this.createPageStyleElement = function(id )
						{
							var htmlAry = new Array();
							var zindex = this.UIIndex;
							var coverclass = "coverDivClear";
							if(this.TYPE == this.MSG || this.TYPE == this.DIALOG)
							{
								zindex = zindex + 5;
								coverclass = "coverDivClear" ;
							}
								
								htmlAry.push("<div id='"+this.popupID+"coverDiv' class='"+coverclass+"' style='display:none; z-index:" +zindex+ ";' >");
									htmlAry.push("<iframe id='"+this.popupID+"coverFrame' class='coverFrame' border='0' frameborder='0' src='"+staticServer+"/blank.html'></iframe>");
								htmlAry.push("</div>");
								
							if(this.TYPE == this.PAGE)
							{	
								htmlAry.push("<div class='loading' style='display:none; z-index:"+(zindex+5)+";' id='"+this.popupID+"loader'>");
									htmlAry.push("<div class='loading_inner'><img border=0 src='"+this.LOADING_IMGPATH+"' /></div>");
								htmlAry.push("</div>");
							}
							zindex ++;
							htmlAry.push("<div class='alertMes' id='"+this.popupID+"'  class='FFselectNone' style='display:none;position:absolute; z-index:"+zindex+";' >");
								
								htmlAry.push("<div class='alertMes_inner'  id='"+this.popupID+"_inner'>");

//================= top line ======================//
htmlAry.push("		<div class=\"Float_Left\"  id=\""+this.popupID+"_toppanel\" style=\"margin:0px;height:5px;line-height:5px;border-top:1px solid #0159BA;border-left:1px solid #0159BA;border-right:1px solid #0159BA;background-color:#D3E8FD;\">       ");
htmlAry.push("			&nbsp;       ");
htmlAry.push("		<\/div>       ");
htmlAry.push("		<div class=\"Clearboth\"><\/div>       ");

//================= title line ======================//
htmlAry.push("		<div class=\"Float_Left\" style=\"width:5px;height:26px;border-left:1px solid #0159BA;background-color:#D3E8FD;overflow:hidden;\">&nbsp;       ");
htmlAry.push("		<\/div>       ");
htmlAry.push("		<div class=\"Float_Left\" onselectstart=\"return false\"  id=\""+this.popupID+"_top_center\"  style='background-color:white;height:26px;cursor:move;'   ");
htmlAry.push("				onselect=\"document.selection.empty()\"       ");
htmlAry.push("				onmousedown=\"if("+this.popupID+".isLOCKING)return ;"+this.popupID+".mover.Move(event)\"       ");
htmlAry.push("				style=\"\"       ");
htmlAry.push("				valign=\"bottom\" >       ");
htmlAry.push("					<span id=\""+this.popupID+"_title\" class=\"alertMes_inner_title\"><\/span>       ");
htmlAry.push("		<\/div>     	  ");

htmlAry.push("		<div class=\"Float_Left\" style=\"height:26px;background-color:white;\" >       ");	
htmlAry.push("					<div style='margin-top:5px;width:24px;overflow:hidden;'> 		");	//total width: 24px , img width:16px , margin right: 8px
htmlAry.push("						<img src=\""+this.APP_ROOTPATH+"\/images\/icon-cross.gif?v=201007121651\" onmousedown=\"if(document.getElementById('"+this.popupID+"_ifr')!=null)document.getElementById('"+this.popupID+"_ifr').focus();"+this.popupID+".XClose();return false;\"       ");
htmlAry.push("						style=\"cursor: pointer;\" border=\"0\" \/>   ");
htmlAry.push("					</div>     ");
htmlAry.push("		<\/div>       ");
htmlAry.push("		<div class=\"Float_Left\" style=\"width:5px;height:26px;border-right:1px solid #0159BA;background-color:#D3E8FD;overflow:hidden;\">&nbsp;       ");
htmlAry.push("		<\/div>       ");
		
htmlAry.push("		<div class=\"Clearboth\"><\/div>       ");

//================= content ======================//
htmlAry.push("		<div class=\"Float_Left\" id=\""+this.popupID+"_contentpanel_left\" style=\"width:5px;height:26px;border-left:1px solid #0159BA;background-color:#D3E8FD;\">       ");
htmlAry.push("		<\/div>       ");
htmlAry.push("			<div class=\"Float_Left\" style=\"padding-left:10px;padding-right:10px;padding-bottom:10px;background-color:#FFFFFF;\"    ");
htmlAry.push("								id=\""+this.popupID+"_content\" class=\"alertMes_inner_content\"       ");
htmlAry.push("								align=\"center\">       ");
htmlAry.push("			<\/div>       ");
htmlAry.push("		<div class=\"Float_Left\" id=\""+this.popupID+"_contentpanel_right\" style=\"width:5px;height:26px;border-right:1px solid #0159BA;background-color:#D3E8FD;\">       ");
htmlAry.push("		<\/div>       ");

htmlAry.push("		<div class=\"Clearboth\"><\/div>       ");

//================= bottom line ======================//
htmlAry.push("		<div id=\""+this.popupID+"_bottompanel\" style=\"height:5px;line-height:5px;border-bottom:1px solid #0159BA;border-left:1px solid #0159BA;border-right:1px solid #0159BA;background-color:#D3E8FD;\">       ");
htmlAry.push("			&nbsp;       ");
htmlAry.push("		<\/div>       ");

									
								htmlAry.push("</div>");
								
							htmlAry.push("</div>");
							
							document.write(htmlAry.join(''));
						}
						
						this.XClose = function ()
						{
							if(this.isLOCKING)return ;
							
							if(this.BeforeXCloseEvent !=null)
							{
								this.exeEevent(this.BeforeXCloseEvent);
							}
							
							if(this.XCloseCallback == null)
								this.closePopup(1);
							else
							{
								this.closePopup(0);  // not to exe callback event
								this.exeEevent(this.XCloseCallback);
							}
						}
						
						this.sendXMLData = function (xml)     
						{
							
							if(xml == null) xml ="";
								this.IFRAME_CALLBACK_XMLDATA = recordsFromXML(xml);
							
							this.onCatchXMLData();
							
						}
						this.setTempXMLData = function (xml)
						{
							if(xml == null) xml ="";
								this.TEMP_XMLDATA = recordsFromXML(xml);
							
						}
						this.onCatchXMLData = function ()  // please override 
						{
							try
						   	{ 
						   		var tf = this.CallBackEVENT.indexOf("(") > 0 && this.CallBackEVENT.indexOf(")") > 0;
								eval( this.CallBackEVENT+(tf ? "" : "()") );
							}
							catch(err){
							}
						}
						this.getCallBackXMLData = function ()
						{
							return this.IFRAME_CALLBACK_XMLDATA ;
						}
						this.getTempXMLData = function ()
						{
							return this.TEMP_XMLDATA ;
						}
						
						this.setParent = function (pageobj)  // one-off
						{
							this.ParentID = pageobj.popupID ;
							this.isChildEVENT = true;
							//if(this.TYPE == this.PAGE)
							this.SnapUserID = null;
							
						}
						
						this.setSnapUser = function (snapid,pageobj) // one-off
						{
							this.ParentID = pageobj.popupID ;
							this.SnapUserID = snapid;
							this.isChildEVENT = true;
							//---------no snap , then delete these code
							try
							{
								snap.setMouseOutEvent();   // click a button , snap will not hide
					   			this.closedEvent = function () {  snap.revertMouseOutEvent();  };
						   	}
						   	catch(err)
						   	{}
						   	//-------------
						}
						

						


		}
		function recordsFromXML(xmlstr)
		{
				var responseXML;
				if(document.all)
				{
					var xmlDom=new ActiveXObject("Microsoft.XMLDOM")
					xmlDom.loadXML(xmlstr)
					responseXML =  xmlDom
				}
				else
					responseXML =  new DOMParser().parseFromString(xmlstr, "text/xml")
				
				var streva ="";
				try
				{
						var data = responseXML.getElementsByTagName("List");
						var dchild = data[0].childNodes;
						var count = dchild.length;
						var datalist = new Array(count);
						
						for(var j=0;j < count;j++)
						{
						
							var childrens = dchild[j].childNodes;
							
							for(var i=0;i<childrens.length;i++) 
							{
								var child = childrens[i];
								
								if(child.nodeType == 1) 
								{
									streva += child.tagName +" : \""+child.childNodes[0].nodeValue+"\" ," ;
								}
								else
								if(child.nodeType == 3) 
								{
									streva += dchild[j].tagName +" : \""+child.nodeValue+"\" ," ;
									
								}
							}

							if(streva != "")
								streva = streva.substring(0,streva.length-1);
							
							eval(
									"	var data ={   " +
											streva +

												"};  "
								);
								
							datalist[j] = data;
							streva = "";
						}
						
						return datalist;
					}
				catch (err)
				{
						
							var childrens = responseXML.childNodes[0].childNodes;
							
							for(var i=0;i<childrens.length;i++) 
							{
								var child = childrens[i];
								if(child.nodeType == 1) 
								{
									var val="";
									if(child.childNodes[0] != null)
										val = child.childNodes[0].nodeValue ;
									streva += child.tagName +" : \""+val+"\" ," ;
								}
							}
							
							if(streva != "")
								streva = streva.substring(0,streva.length-1);
						
								eval(
										"	var data ={   " +
												streva +
	
													"};  "
								);
							
							return data;
				}
		}
		
		
		/*
		function recordsFromXMLOLD(xmlstr)
		{
				if(xmlstr == null || xmlstr == "") return null;
				var responseXML;
				if(document.all)
				{
					var xmlDom=new ActiveXObject("Microsoft.XMLDOM")
					xmlDom.loadXML(xmlstr)
					responseXML =  xmlDom
				}
				else
					responseXML =  new DOMParser().parseFromString(xmlstr, "text/xml")

				var streva ="";
				var childrens = responseXML.childNodes[0].childNodes;

				for(var i=0;i<childrens.length;i++) 
				{
					var child = childrens[i];
					if(child.nodeType == 1) 
					{
						streva += child.tagName +" : '"+child.childNodes[0].nodeValue+"' ," ;
					}
				}

				if(streva != "")
					streva = streva.substring(0,streva.length-1);
				
					eval(
							"	var data ={   " +
									streva +
	
										"};  "
					);
				
				

				return data;
		}
		*/
///-------------------End---------------------------------//



////////////////////////////////////////////////////////////////////////////////////
///           Popup  View Object     ###By James	   2008-1-24
/////////////////////////////////////////////////////////////////////////

function Viewer(vid)
{			
						this.viewID = vid;
						this.show_timestep = 5 ;
						this.show_opacitystep = 30 ;

						this.hidden_timestep = 10 ;
						this.hidden_opacitystep = 30 ;
						
						this.show_slowly = false;    // set pop-up window slowly 
						this.hide_slowly = false;
						
						this.changeshowvar = 0;
						this.tempOverFlow = "";
						this.change_show = function(id)
						{
						   var obj = $(id);
						   this.changeshowvar += this.show_opacitystep; 
						   obj.style.filter = "Alpha(Opacity=" + this.changeshowvar + ")";
						   obj.style.opacity = this.changeshowvar/100;
						   if(this.changeshowvar>=100)
						   {
								this.changeshowvar=0;
								try
								{
									$(id).focus();
								}catch(err){}
								this.showed();   // do something after showed 
								
						   }
						   else
							    setTimeout(this.viewID+".change_show('"+id+"')",this.show_timestep);
						}

						this.changehiddenvar = 100;
						
						this.change_hidden = function(id)
						{
						   var obj = $(id);
						  
						   this.changehiddenvar -= this.hidden_opacitystep;
						   obj.style.filter = "Alpha(Opacity=" + this.changehiddenvar + ")";
						   obj.style.opacity = this.changehiddenvar/100; 
						
						   if(this.changehiddenvar<=0)
						   {
						   		
								obj.style.display="none";
								this.changehiddenvar=100;
								this.hiddened();  // do something after hidden 
								this.viewScrollBar(true);
								return ;
						   }
						   else
							  setTimeout(this.viewID+".change_hidden('"+id+"')",this.hidden_timestep);
						}
						
						this.show = function(id)        //////////////show
						{

						  if(this.show_slowly)
     					  {
							  $(id).style.filter = "Alpha(Opacity="+this.changeshowvar+")";
							  $(id).style.display=""; 
						  }
						  else
						  {
						  		$(id).style.display="";
						  		this.changeshowvar = 100;
						  }
								
						  //setTimeout(this.viewID+".change_show('"+id+"')",1);
						  
						  this.viewScrollBar(false);
						  
						   this.change_show(id);
						   document.onkeydown = function (event)
							{
									var eve=event||window.event;
							
									if(eve.keyCode==9)	
									{
										return false; 	// tab button disabled
									} 
							}
						
						}
						
						this.hidden = function(id)     //////////////hidden
						{
							if(!this.hide_slowly)
     						{
								$(id).style.display="none";
								this.changehiddenvar = 0 ;
							}
							
							//setTimeout(this.viewID+".change_hidden('"+id+"')",1);
							this.change_hidden(id);	
							document.onkeydown = function (event)
							{
									var eve=event||window.event;
							
									if(eve.keyCode==9)
									{
										return true;     // tab button enabled
									}
							}
						}
						this.viewScrollBar = function(tf)
						{
							return ;   // disabled
							var temp_h1 = document.body.clientHeight;
							var temp_h2 = document.documentElement.clientHeight;
							var isXhtml = (temp_h2<=temp_h1&&temp_h2!=0)?true:false; 
							var htmlbody = isXhtml?document.documentElement:document.body;
							
							if(tf)
								htmlbody.style.overflow = this.tempOverFlow;
							else
							{
								this.tempOverFlow = htmlbody.style.overflow;
								htmlbody.style.overflow = "hidden";
							}
							
						}
						this.showed = function()   // please override 
						{
						}
						this.hiddened = function()  // please override 
						{
						}
						

}




////////////////////////////////////
///        common function
/////////////////////////////////////////
function $(elementid)
{  
	var obj;
	try
	{
		obj = document.getElementById(elementid);
	}
	catch (err)
	{
		//alert(elementid+" NOT Found!");
	}
	return obj;
}

function getBodyObj() 
{
	var e=document.documentElement;
	var _t = {};
	_t.clientHeight = e.clientHeight;
	_t.clientWidth = e.clientWidth;
	
	_t.scrollLeft=e.scrollLeft;
	_t.scrollTop=e.scrollTop;
	
	_t.offsetWidth=e.offsetWidth;
	_t.offsetHeight=e.offsetHeight;
	
	_t.scrollHeight = e.scrollHeight;
	_t.scrollWidth = e.scrollWidth;
	
	if(checkBrowser()==3){
		_t.scrollLeft=document.body.scrollLeft;
		_t.scrollTop=document.body.scrollTop;
	}
    return _t; 
}

function checkBrowser()
{		
	if ( navigator.userAgent.indexOf("MSIE")>0 )
		return 1;
	if ( isFirefox=navigator.userAgent.indexOf("Firefox")>0 )
		return 2;
	if ( isSafari=navigator.userAgent.indexOf("Safari")>0 ) //google
		return 3;
	if ( isCamino=navigator.userAgent.indexOf("Camino")>0 )
		return 4;
	if ( isMozilla=navigator.userAgent.indexOf("Gecko/")>0)
		return 5;
	return 0;
}
	
/////////////////////////////////////////



////////////////////////////////////////
///			Popup Scroll Move
////////////////////////////////////////

  var scrollTimer = null;
  var prewScrollTop = 0;
  var MoveStep = 20;
  var MoveTimeStep = 10;

  function popupSetScroll(popIdAry)
  {
  		window.onscroll = function (){ scrollPopup(popIdAry); }
  }
  
  function scrollPopup(popIdAry)   
  {   
	  if(scrollTimer != null)
		  clearTimeout(scrollTimer);

		scrollTimer = setTimeout(function (){scrollEnd(popIdAry)} , 500);
  }
	
   function scrollEnd(idAry)
   {
			if(checkUpOrDown() == "up")
				goTop(idAry , getScroll().t+120 , MoveStep , MoveTimeStep );
			else
				goDown(idAry , getScroll().t+120 , MoveStep , MoveTimeStep );
			
			prewScrollTop = getScroll().t;
   }

   function checkUpOrDown()
   {
		var bodyOffsetTop = getScroll().t;

		if(prewScrollTop < bodyOffsetTop)
		{
			return "down";
		}
		else
			return "up";
   }

   function goTop(objIdAry , maxTop , topStep , timeStep)
   {
   		var n = 0;
		for(var i=0;i<objIdAry.length;i++)
		{	
			try
			{
				if(document.getElementById(objIdAry[i]).style.display == "none")
					continue;
				
	
				maxTop = getBodyObj().scrollTop + (getBodyObj().clientHeight- $(objIdAry[i]).style.height.substring(0,$(objIdAry[i]).style.height.length-2))/2;
					
				n = _goTop(objIdAry[i], maxTop , topStep , timeStep);
			}catch(err){}
		}
		
		if( n == 1)
				setTimeout(function (){ goTop(objIdAry , maxTop , topStep , timeStep); } , timeStep);
		
   }

   function _goTop(objId , maxTop , topStep , timeStep)
   {
		var obj = document.getElementById(objId);
		var objTop = obj.style.top.substring(0,obj.style.top.length-2);
		
		if(objId == "popupPage")
			maxTop = getScroll().t +110;
		
		if( (objTop*1-topStep*1) <= maxTop)
		{
			obj.style.top = maxTop+"px";
			return 0;
		}
		else
		{
			obj.style.top = (objTop*1-topStep*1)+"px";
			return 1;
		}
   }
  
   function goDown(objIdAry , maxTop , topStep , timeStep)
   {
   		var n = 0;
		for(var i=0;i<objIdAry.length;i++)
		{
			try
			{
				if(document.getElementById(objIdAry[i]).style.display == "none")
					continue;
					
				maxTop = getBodyObj().scrollTop + (getBodyObj().clientHeight- $(objIdAry[i]).style.height.substring(0,$(objIdAry[i]).style.height.length-2))/2;
					
				n = _goDown(objIdAry[i], maxTop , topStep , timeStep);
			}catch(err){}
		}
		
		if( n == 1)
				setTimeout(function (){ goDown(objIdAry , maxTop , topStep , timeStep); } , timeStep);
   }

   function _goDown(objId , maxTop , topStep , timeStep)
   {
		var obj = document.getElementById(objId);
		var objTop = obj.style.top.substring(0,obj.style.top.length-2);
		
		if(objId == "popupPage")
			maxTop = getScroll().t +110;
			
		if( (objTop*1+topStep*1) >= maxTop )
		{
			obj.style.top = maxTop+"px";	
			return 0;
		}
		else
		{
			obj.style.top = (objTop*1+topStep*1)+"px";
			return 1;
		}
   }

    function getScroll()  
	{ 
		var t, l, w, h; 
		 
		if (document.documentElement && document.documentElement.scrollTop) { 
			t = document.documentElement.scrollTop; 
			l = document.documentElement.scrollLeft; 
			w = document.documentElement.scrollWidth; 
			h = document.documentElement.scrollHeight; 
		} else if (document.body) { 
			t = document.body.scrollTop; 
			l = document.body.scrollLeft; 
			w = document.body.scrollWidth; 
			h = document.body.scrollHeight; 
		} 
		return { t: t, l: l, w: w, h: h }; 
	} 



var DateFormat= new DateUtil();
DateFormat.Init();


function DateUtil(){
	this.defaultFormat = "YYYY/MM/DD hh:mm:ss";
	this.language;
	this.langformat = {
		zh:"YYYY年MM月DD日 hh:mm:ss",
		us:"YYYY/MM/DD hh:mm:ss",
		en:"DD/MM/YYYY hh:mm:ss",
		ca:"DD/MM/YYYY hh:mm:ss",
		de:"DD/MM/YYYY hh:mm:ss",
		fr:"DD/MM/YYYY hh:mm:ss"
	}
	
	this.Init = function(){
		if(this.language==null){
			this.language = this.checkLanguage();
		}
		this.language = this.language.toLowerCase();
		 for ( var   p in this.langformat){
		 	if(this.language.indexOf(p)>-1)
		 	{
		 		this.defaultFormat = this.langformat[p];
		 		break;
		 	}
   		 }   
      	}
	
	this.setLanguage = function(lang){
		this.language =lang;
		this.Init();
	}
	
	this.checkLanguage = function ()
	{
		if ( navigator.userAgent.indexOf("MSIE")>0 )
			return window.navigator.systemLanguage;
		if ( navigator.userAgent.indexOf("Firefox")>0 )
			return navigator.language;
		if ( isSafari=navigator.userAgent.indexOf("Safari")>0 )
			return "zh";
		if ( isCamino=navigator.userAgent.indexOf("Camino")>0 )
			return "zh";
		if ( isMozilla=navigator.userAgent.indexOf("Gecko/")>0)
			return "zh";
		return "zh";
	}
		
	
	this.toLocaleString =function(date){
		return this.Format(this.defaultFormat,date);		//Default native browser 'toLocaleString()' implementation. May vary by browser. Example: Friday, November 04, 2008 11:03:00 AM
	}
	this.toUSShortDate=function(date){
		return this.Format("MM/DD/YYYY",date);		//Short date in format MM/DD/YYYY.Example: 11/4/2008
	}
	this.toUSShortDateTime=function(date){
		return this.Format("MM/DD/YYYY hh:mm:ss",date);		//Short date with time in format MM/DD/YYYY HH:MM. Example: 11/4/2008 11:03
	}
	this.toEuropeanShortDate=function(date){
		return this.Format("DD/MM/YYYY",date);		//Short date in format DD/MM/YYYY. Example: 4/11/2008
	}
	this.toEuropeanShortDateTime=function(date){
		return this.Format("DD/MM/YYYY hh:mm:ss",date);		//Short date with time in format DD/MM/YYYY HH:MM.   Example: 4/11/2008 11:03
	}
	this.toJapanShortDate =function(date){
		return this.Format("YYYY/MM/DD",date);		//Short date in format YYYY/MM/DD.  Example: 2008/11/4
	}
	this.toJapanShortDateTime =function(date){
		return this.Format("YYYY/MM/DD hh:mm:ss",date);		//Short date with time in format YYYY/MM/DD HH:MM  Example: 2008/11/4 11:03
	}
	this.toChinaShortDate = function(date){
		return this.Format("YYYY年MM月DD日",date);	//Short date in format YYYY年MM月DD日  Example: 2008年11月4日
	}	
	this.toMidLineDate = function(date){
		return this.Format("YYYY-MM-DD hh:mm",date);	
	}	
	this.toCalendarDate = function(date){
		return this.Format("YYYY-MM-DD",date);	
	}	
	this.toChinaShortDateTime = function(date){
		return this.Format("YYYY年MM月DD日 hh:mm:ss",date);	//Short date with time in format YYYY年MM月DD日  Example: 2008年11月4日 11:03:00
	}

	this.Format=function(fmtCode,date){
		try{
			date=date.replaceAll("-","/");
		}catch(err){
		
		}
		if(!fmtCode){fmtCode="YYYY/MM/DD hh:mm:ss";}   
		if(date)
		{
			d=new Date(date);
			if(isNaN(d)){
				return "Invalid Date";
			}
		}
		else
		{
			d=new Date();
		}
		arr_d=this.splitDate(d,true);
		var str=fmtCode;
		str = str.replace("YYYY",arr_d.YYYY);
		str = str.replace("MM",arr_d.MM);
		str = str.replace("DD",arr_d.DD);
		str = str.replace("hh",arr_d.hh);
		str = str.replace("mm",arr_d.mm);
		str = str.replace("ss",arr_d.ss);
		str = str.replace("00:00:00","");
		return str;   
	};




	this.splitDate = function (d,isZero){   
		var YYYY,MM,DD,hh,mm,ss;   
		YYYY=d.getFullYear();   
		MM=(d.getMonth()+1)<10?"0"+(d.getMonth()+1):d.getMonth()+1;   
		DD=d.getDate()<10?"0"+d.getDate():d.getDate();   
		hh=d.getHours()<10?"0"+d.getHours():d.getHours();   
		mm=d.getMinutes()<10?"0"+d.getMinutes():d.getMinutes();   
		ss=d.getSeconds()<10?"0"+d.getSeconds():d.getSeconds();   
		return {"YYYY":YYYY,"MM":MM,"DD":DD,"hh":hh,"mm":mm,"ss":ss};     
	}   
}

/*
Demo:

var str= DateFormat.toChinaShortDateTime("2008/02-05 10:12:00");
alert(str);
document.write(str);
*/

//UserData:For Local Storage..
//Author:Kim
function saveUserData(name, value) {
        var argv = saveUserData.arguments;
        var argc = saveUserData.arguments.length;
        var expires = new Date();
        //var path = (argc > 3) ? argv[3] : null;
		var path="/";
        var domain = (argc > 4) ? argv[4] : null;

        expires.setYear(expires.getFullYear()+1);
        expires.setMonth(10);
        expires.setDate(1);
        expires.setHours(2);
        expires.setMinutes(3);
		var tvalue=""+value+"";
        st = name+"="+Base64.encode(tvalue)+"; expires=" + expires.toGMTString()+ ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) ;
         document.cookie =st;
}

function loadUserData(name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg) {
                        offset=j;
                        var endstr = document.cookie.indexOf (";", offset);
                        if (endstr == -1)
                                endstr = document.cookie.length;
                        return Base64.decode(document.cookie.substring(offset, endstr));
                }
                i = document.cookie.indexOf(" ", i) + 1;
                if (i == 0)
                        break;
        }
        return null;
}

function deleteUserData(name) {
        var expdate = new Date ();
        expdate.setTime (expdate.getTime()-1);
        saveUserData (name, "", expdate)
}

 
/*
 * 2009 Kim. All the *_ACTION.js is here.
 */
var _RPC_Path = "/dwr";

if(window.location.href.indexOf("/BMH-New")>0){
	_RPC_Path="/BMH-New/dwr";
}
if(window.location.href.indexOf("/v50")>0){
	_RPC_Path="/v50/dwr";
}

if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;


/* TRADER_ACTION.js */
if (TRADER_ACTION == null) var TRADER_ACTION = {};
TRADER_ACTION._path = _RPC_Path;
TRADER_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(TRADER_ACTION._path, 'TRADER_ACTION', 'callRPC', p0, false, false, callback);
}


/* ATTACHMENT_ACTION.js */
if (ATTACHMENT_ACTION == null) var ATTACHMENT_ACTION = {};
ATTACHMENT_ACTION._path = _RPC_Path;
ATTACHMENT_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(ATTACHMENT_ACTION._path, 'ATTACHMENT_ACTION', 'callRPC', p0, false, false, callback);
}


/* MLM_ACTION.js */
if (MLM_ACTION == null) var MLM_ACTION = {};
MLM_ACTION._path = _RPC_Path;
MLM_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MLM_ACTION._path, 'MLM_ACTION', 'callRPC', p0, false, false, callback);
}



/* PAYMENT_ACTION.js */
if (PAYMENT_ACTION == null) var PAYMENT_ACTION = {};
PAYMENT_ACTION._path = _RPC_Path;
PAYMENT_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(PAYMENT_ACTION._path, 'PAYMENT_ACTION', 'callRPC', p0, false, false, callback);
}


/* MEMBER_ACTION.js */
if (MEMBER_ACTION == null) var MEMBER_ACTION = {};
MEMBER_ACTION._path = _RPC_Path;
MEMBER_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_ACTION._path, 'MEMBER_ACTION', 'callRPC', p0, false, false, callback);
}

/* MEMBER_INFO_ACTION.js */
if (MEMBER_INFO_ACTION == null) var MEMBER_INFO_ACTION = {};
MEMBER_INFO_ACTION._path = _RPC_Path;
MEMBER_INFO_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_INFO_ACTION._path, 'MEMBER_INFO_ACTION', 'callRPC', p0, false, false, callback);
}

/* PUBLIC_ACTION.js */
if (PUBLIC_ACTION == null) var PUBLIC_ACTION = {};
PUBLIC_ACTION._path = _RPC_Path;
PUBLIC_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(PUBLIC_ACTION._path, 'PUBLIC_ACTION', 'callRPC', p0, false, false, callback);
}



/* ACCOUNT_ACTION.js */
if (ACCOUNT_ACTION == null) var ACCOUNT_ACTION = {};
ACCOUNT_ACTION._path = _RPC_Path;
ACCOUNT_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(ACCOUNT_ACTION._path, 'ACCOUNT_ACTION', 'callRPC', p0, false, false, callback);
}



/* SEARCH_ACTION.js */
if (SEARCH_ACTION == null) var SEARCH_ACTION = {};
SEARCH_ACTION._path = _RPC_Path;
SEARCH_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(SEARCH_ACTION._path, 'SEARCH_ACTION', 'callRPC', p0, false, false, callback);
}



/* SELL_SOLUTION_ACTION.js */
if (SELL_SOLUTION_ACTION == null) var SELL_SOLUTION_ACTION = {};
SELL_SOLUTION_ACTION._path = _RPC_Path;
SELL_SOLUTION_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(SELL_SOLUTION_ACTION._path, 'SELL_SOLUTION_ACTION', 'callRPC', p0, false, false, callback);
}


/* SELL_SERVICE_ACTION.js */
if (SELL_SERVICE_ACTION == null) var SELL_SERVICE_ACTION = {};
SELL_SERVICE_ACTION._path = _RPC_Path;
SELL_SERVICE_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(SELL_SERVICE_ACTION._path, 'SELL_SERVICE_ACTION', 'callRPC', p0, false, false, callback);
}


/* BUY_STANDARD_ACTION.js */
if (BUY_STANDARD_ACTION == null) var BUY_STANDARD_ACTION = {};
BUY_STANDARD_ACTION._path = _RPC_Path;
BUY_STANDARD_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(BUY_STANDARD_ACTION._path, 'BUY_STANDARD_ACTION', 'callRPC', p0, false, false, callback);
}



/* BUY_AWARDOFFER_ACTION.js */
if (BUY_AWARDOFFER_ACTION == null) var BUY_AWARDOFFER_ACTION = {};
BUY_AWARDOFFER_ACTION._path = _RPC_Path;
BUY_AWARDOFFER_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(BUY_AWARDOFFER_ACTION._path, 'BUY_AWARDOFFER_ACTION', 'callRPC', p0, false, false, callback);
}



/* TRADER_ACTION.js */
if (TRADER_ACTION == null) var TRADER_ACTION = {};
TRADER_ACTION._path = _RPC_Path;
TRADER_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(TRADER_ACTION._path, 'TRADER_ACTION', 'callRPC', p0, false, false, callback);
}


/* TRADING_STATUS_ACTION.js */
if (TRADING_STATUS_ACTION == null) var TRADING_STATUS_ACTION = {};
TRADING_STATUS_ACTION._path = _RPC_Path;
TRADING_STATUS_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(TRADING_STATUS_ACTION._path, 'TRADING_STATUS_ACTION', 'callRPC', p0, false, false, callback);
}

/* REPLY_ACTION.js */
if (REPLY_ACTION == null) var REPLY_ACTION = {};
REPLY_ACTION._path = _RPC_Path;
REPLY_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(REPLY_ACTION._path, 'REPLY_ACTION', 'callRPC', p0, false, false, callback);
}


/* WATCH_LIST_ACTION.js */
if (WATCH_LIST_ACTION == null) var WATCH_LIST_ACTION = {};
WATCH_LIST_ACTION._path = _RPC_Path;
WATCH_LIST_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(WATCH_LIST_ACTION._path, 'WATCH_LIST_ACTION', 'callRPC', p0, false, false, callback);
}

/* WATCH_LIST_ACTION.js */
if (SEARCH_POST_ACTION == null) var SEARCH_POST_ACTION = {};
SEARCH_POST_ACTION._path = _RPC_Path;
SEARCH_POST_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(SEARCH_POST_ACTION._path, 'SEARCH_POST_ACTION', 'callRPC', p0, false, false, callback);
}

if (PUBLICACTION == null) var PUBLICACTION = {};
PUBLICACTION._path = _RPC_Path;
PUBLICACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(PUBLICACTION._path, 'PUBLICACTION', 'callRPC', p0, false, false, callback);
}


if (SEARCH_FEEDBACK_COM_ACTION == null) var SEARCH_FEEDBACK_COM_ACTION = {};
SEARCH_FEEDBACK_COM_ACTION._path = _RPC_Path;
SEARCH_FEEDBACK_COM_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(SEARCH_FEEDBACK_COM_ACTION._path, 'SEARCH_FEEDBACK_COM_ACTION', 'callRPC', p0, false, false, callback);
}


if (MEMBER_CREDIT_ACTION == null) var MEMBER_CREDIT_ACTION = {};
MEMBER_CREDIT_ACTION._path = _RPC_Path;
MEMBER_CREDIT_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_CREDIT_ACTION._path, 'MEMBER_CREDIT_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_MESSAGE_ACTION == null) var MEMBER_MESSAGE_ACTION = {};
MEMBER_MESSAGE_ACTION._path = _RPC_Path;
MEMBER_MESSAGE_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_MESSAGE_ACTION._path, 'MEMBER_MESSAGE_ACTION', 'callRPC', p0, false, false, callback);
}

if (ATTACHMENT_ACTION == null) var ATTACHMENT_ACTION = {};
ATTACHMENT_ACTION._path = _RPC_Path;
ATTACHMENT_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(ATTACHMENT_ACTION._path, 'ATTACHMENT_ACTION', 'callRPC', p0, false, false, callback);
}

if (BUY_QUESTION_ACTION == null) var BUY_QUESTION_ACTION = {};
BUY_QUESTION_ACTION._path = _RPC_Path;
BUY_QUESTION_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(BUY_QUESTION_ACTION._path, 'BUY_QUESTION_ACTION', 'callRPC', p0, false, false, callback);
}

if (BUY_TRADING_ACTION == null) var BUY_TRADING_ACTION = {};
BUY_TRADING_ACTION._path = _RPC_Path;
BUY_TRADING_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(BUY_TRADING_ACTION._path, 'BUY_TRADING_ACTION', 'callRPC', p0, false, false, callback);
}

if (COMISSION_ACTION == null) var COMISSION_ACTION = {};
COMISSION_ACTION._path = _RPC_Path;
COMISSION_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(COMISSION_ACTION._path, 'COMISSION_ACTION', 'callRPC', p0, false, false, callback);
}

if (FEEDBACK_ACTION == null) var FEEDBACK_ACTION = {};
FEEDBACK_ACTION._path = _RPC_Path;
FEEDBACK_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(FEEDBACK_ACTION._path, 'FEEDBACK_ACTION', 'callRPC', p0, false, false, callback);
}

if (HANDLING_CHARGE_ACTION == null) var HANDLING_CHARGE_ACTION = {};
HANDLING_CHARGE_ACTION._path = _RPC_Path;
HANDLING_CHARGE_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(HANDLING_CHARGE_ACTION._path, 'HANDLING_CHARGE_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_NEW_ACTION == null) var MEMBER_NEW_ACTION = {};
MEMBER_NEW_ACTION._path = _RPC_Path;
MEMBER_NEW_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_NEW_ACTION._path, 'MEMBER_NEW_ACTION', 'callRPC', p0, false, false, callback);
}
if (MEMBER_PREF_ACTION == null) var MEMBER_PREF_ACTION = {};
MEMBER_PREF_ACTION._path = _RPC_Path;
MEMBER_PREF_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_PREF_ACTION._path, 'MEMBER_PREF_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_IDENTITY_ACTION == null) var MEMBER_IDENTITY_ACTION = {};
MEMBER_IDENTITY_ACTION._path = _RPC_Path;
MEMBER_IDENTITY_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_IDENTITY_ACTION._path, 'MEMBER_IDENTITY_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_FUND_ACTION == null) var MEMBER_FUND_ACTION = {};
MEMBER_FUND_ACTION._path = _RPC_Path;
MEMBER_FUND_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_FUND_ACTION._path, 'MEMBER_FUND_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_FUND_SETTING_ACTION == null) var MEMBER_FUND_SETTING_ACTION = {};
MEMBER_FUND_SETTING_ACTION._path = _RPC_Path;
MEMBER_FUND_SETTING_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_FUND_SETTING_ACTION._path, 'MEMBER_FUND_SETTING_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_TPL_ACTION == null) var MEMBER_TPL_ACTION = {};
MEMBER_TPL_ACTION._path = _RPC_Path;
MEMBER_TPL_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_TPL_ACTION._path, 'MEMBER_TPL_ACTION', 'callRPC', p0, false, false, callback);
}

if (MEMBER_TRANSFER_ACTION == null) var MEMBER_TRANSFER_ACTION = {};
MEMBER_TRANSFER_ACTION._path = _RPC_Path;
MEMBER_TRANSFER_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_TRANSFER_ACTION._path, 'MEMBER_TRANSFER_ACTION', 'callRPC', p0, false, false, callback);
}
if (MEMBER_WITHDRAW_SETTING_ACTION == null) var MEMBER_WITHDRAW_SETTING_ACTION = {};
MEMBER_WITHDRAW_SETTING_ACTION._path = _RPC_Path;
MEMBER_WITHDRAW_SETTING_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(MEMBER_WITHDRAW_SETTING_ACTION._path, 'MEMBER_WITHDRAW_SETTING_ACTION', 'callRPC', p0, false, false, callback);
}

if (PUBLIC_NEW_ACTION == null) var PUBLIC_NEW_ACTION = {};
PUBLIC_NEW_ACTION._path = _RPC_Path;
PUBLIC_NEW_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(PUBLIC_NEW_ACTION._path, 'PUBLIC_NEW_ACTION', 'callRPC', p0, false, false, callback);
}




if (TRADING_RECORD_ACTION == null) var TRADING_RECORD_ACTION = {};
TRADING_RECORD_ACTION._path = _RPC_Path;
TRADING_RECORD_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(TRADING_RECORD_ACTION._path, 'TRADING_RECORD_ACTION', 'callRPC', p0, false, false, callback);
}

if (SIGNUP_ACTION == null) var SIGNUP_ACTION = {};
SIGNUP_ACTION._path = _RPC_Path;
SIGNUP_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(SIGNUP_ACTION._path, 'SIGNUP_ACTION', 'callRPC', p0, false, false, callback);
}

if (COMPLAIN_ACTION == null) var COMPLAIN_ACTION = {};
COMPLAIN_ACTION._path = _RPC_Path;
COMPLAIN_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(COMPLAIN_ACTION._path, 'COMPLAIN_ACTION', 'callRPC', p0, false, false, callback);
}
/* ___ACTION */
if (BENEFICENCE_ACTION == null) var BENEFICENCE_ACTION = {};
BENEFICENCE_ACTION._path = _RPC_Path;
BENEFICENCE_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(BENEFICENCE_ACTION._path, 'BENEFICENCE_ACTION', 'callRPC', p0, false, false, callback);
}
/* ___ACTION */

if (COMMODITY_ACTION == null) var COMMODITY_ACTION = {};
COMMODITY_ACTION._path = _RPC_Path;
COMMODITY_ACTION.callRPC = function(p0, callback) {
  dwr.engine._execute(COMMODITY_ACTION._path, 'COMMODITY_ACTION', 'callRPC', p0, false, false, callback);
}
/* ___ACTION */



/* ___ACTION */



/* ___ACTION */



/*
 * Copyright 2005 Joe Walker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Declare an object to which we can add real functions.
 */
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;

/**
 * Set an alternative error handler from the default alert box.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.setErrorHandler = function(handler) {
  dwr.engine._errorHandler = handler;
};

/**
 * Set an alternative warning handler from the default alert box.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.setWarningHandler = function(handler) {
  dwr.engine._warningHandler = handler;
};

/**
 * Setter for the text/html handler - what happens if a DWR request gets an HTML
 * reply rather than the expected Javascript. Often due to login timeout
 */
dwr.engine.setTextHtmlHandler = function(handler) {
  dwr.engine._textHtmlHandler = handler;
};

/**
 * Set a default timeout value for all calls. 0 (the default) turns timeouts off.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.setTimeout = function(timeout) {
  dwr.engine._timeout = timeout;
};

/**
 * The Pre-Hook is called before any DWR remoting is done.
 * @see getahead.org/dwr/browser/engine/hooks
 */
dwr.engine.setPreHook = function(handler) {
  dwr.engine._preHook = handler;
};

/**
 * The Post-Hook is called after any DWR remoting is done.
 * @see getahead.org/dwr/browser/engine/hooks
 */
dwr.engine.setPostHook = function(handler) {
  dwr.engine._postHook = handler;
};

/**
 * Custom headers for all DWR calls
 * @see getahead.org/dwr/????
 */
dwr.engine.setHeaders = function(headers) {
  dwr.engine._headers = headers;
};

/**
 * Custom parameters for all DWR calls
 * @see getahead.org/dwr/????
 */
dwr.engine.setParameters = function(parameters) {
  dwr.engine._parameters = parameters;
};

/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
dwr.engine.XMLHttpRequest = 1;

/** XHR remoting type constant. See dwr.engine.set[Rpc|Poll]Type() */
dwr.engine.IFrame = 2;

/** XHR remoting type constant. See dwr.engine.setRpcType() */
dwr.engine.ScriptTag = 3;

/**
 * Set the preferred remoting type.
 * @param newType One of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setRpcType = function(newType) {
  if (newType != dwr.engine.XMLHttpRequest && newType != dwr.engine.IFrame && newType != dwr.engine.ScriptTag) {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidRpcType", message:"RpcType must be one of dwr.engine.XMLHttpRequest or dwr.engine.IFrame or dwr.engine.ScriptTag" });
    return;
  }
  dwr.engine._rpcType = newType;
};

/**
 * Which HTTP method do we use to send results? Must be one of "GET" or "POST".
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setHttpMethod = function(httpMethod) {
  if (httpMethod != "GET" && httpMethod != "POST") {
    dwr.engine._handleError(null, { name:"dwr.engine.invalidHttpMethod", message:"Remoting method must be one of GET or POST" });
    return;
  }
  dwr.engine._httpMethod = httpMethod;
};

/**
 * Ensure that remote calls happen in the order in which they were sent? (Default: false)
 * @see getahead.org/dwr/browser/engine/ordering
 */
dwr.engine.setOrdered = function(ordered) {
  dwr.engine._ordered = ordered;
};

/**
 * Do we ask the XHR object to be asynchronous? (Default: true)
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setAsync = function(async) {
  dwr.engine._async = async;
};

/**
 * Does DWR poll the server for updates? (Default: false)
 * @see getahead.org/dwr/browser/engine/options
 */
dwr.engine.setActiveReverseAjax = function(activeReverseAjax) {
  if (activeReverseAjax) {
    // Bail if we are already started
    if (dwr.engine._activeReverseAjax) return;
    dwr.engine._activeReverseAjax = true;
    dwr.engine._poll();
  }
  else {
    // Can we cancel an existing request?
    if (dwr.engine._activeReverseAjax && dwr.engine._pollReq) dwr.engine._pollReq.abort();
    dwr.engine._activeReverseAjax = false;
  }
  // TODO: in iframe mode, if we start, stop, start then the second start may
  // well kick off a second iframe while the first is still about to return
  // we should cope with this but we don't
};

/**
 * The default message handler.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.defaultErrorHandler = function(message, ex) {
  dwr.engine._debug("Error: " + ex.name + ", " + ex.message, true);
  if (message == null || message == "") alert("A server error has occured.");
  // Ignore NS_ERROR_NOT_AVAILABLE if Mozilla is being narky
  else if (message.indexOf("0x80040111") != -1) dwr.engine._debug(message);
  else alert(message);
};

/**
 * The default warning handler.
 * @see getahead.org/dwr/browser/engine/errors
 */
dwr.engine.defaultWarningHandler = function(message, ex) {
  dwr.engine._debug(message);
};

/**
 * For reduced latency you can group several remote calls together using a batch.
 * @see getahead.org/dwr/browser/engine/batch
 */
dwr.engine.beginBatch = function() {
  if (dwr.engine._batch) {
    dwr.engine._handleError(null, { name:"dwr.engine.batchBegun", message:"Batch already begun" });
    return;
  }
  dwr.engine._batch = dwr.engine._createBatch();
};

/**
 * Finished grouping a set of remote calls together. Go and execute them all.
 * @see getahead.org/dwr/browser/engine/batch
 */
dwr.engine.endBatch = function(options) {
  var batch = dwr.engine._batch;
  if (batch == null) {
    dwr.engine._handleError(null, { name:"dwr.engine.batchNotBegun", message:"No batch in progress" });
    return;
  }
  dwr.engine._batch = null;
  if (batch.map.callCount == 0) return;

  // The hooks need to be merged carefully to preserve ordering
  if (options) dwr.engine._mergeBatch(batch, options);

  // In ordered mode, we don't send unless the list of sent items is empty
  if (dwr.engine._ordered && dwr.engine._batchesLength != 0) {
    dwr.engine._batchQueue[dwr.engine._batchQueue.length] = batch;
  }
  else {
    dwr.engine._sendData(batch);
  }
};

/** @deprecated */
dwr.engine.setPollMethod = function(type) { dwr.engine.setPollType(type); };
dwr.engine.setMethod = function(type) { dwr.engine.setRpcType(type); };
dwr.engine.setVerb = function(verb) { dwr.engine.setHttpMethod(verb); };
dwr.engine.setPollType = function() { dwr.engine._debug("Manually setting the Poll Type is not supported"); };

//==============================================================================
// Only private stuff below here
//==============================================================================


/** The read page id that we calculate */
dwr.engine._scriptSessionId = null;

/** The function that we use to fetch/calculate a session id */
dwr.engine._getScriptSessionId = function() {
  if (dwr.engine._scriptSessionId == null) {
    dwr.engine._scriptSessionId = dwr.engine._origScriptSessionId + Math.floor(Math.random() * 1000);
  }
  return dwr.engine._scriptSessionId;
};

/** A function to call if something fails. */
dwr.engine._errorHandler = dwr.engine.defaultErrorHandler;

/** For debugging when something unexplained happens. */
dwr.engine._warningHandler = dwr.engine.defaultWarningHandler;

/** A function to be called before requests are marshalled. Can be null. */
dwr.engine._preHook = null;

/** A function to be called after replies are received. Can be null. */
dwr.engine._postHook = null;

/** An map of the batches that we have sent and are awaiting a reply on. */
dwr.engine._batches = {};

/** A count of the number of outstanding batches. Should be == to _batches.length unless prototype has messed things up */
dwr.engine._batchesLength = 0;

/** In ordered mode, the array of batches waiting to be sent */
dwr.engine._batchQueue = [];

/** What is the default rpc type */
dwr.engine._rpcType = dwr.engine.XMLHttpRequest;

/** What is the default remoting method (ie GET or POST) */
dwr.engine._httpMethod = "POST";

/** Do we attempt to ensure that calls happen in the order in which they were sent? */
dwr.engine._ordered = false;

/** Do we make the calls async? */
dwr.engine._async = true;

/** The current batch (if we are in batch mode) */
dwr.engine._batch = null;

/** The global timeout */
dwr.engine._timeout = 0;

/** ActiveX objects to use when we want to convert an xml string into a DOM object. */
dwr.engine._DOMDocument = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];

/** The ActiveX objects to use when we want to do an XMLHttpRequest call. */
dwr.engine._XMLHTTP = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];

/** Are we doing comet or polling? */
dwr.engine._activeReverseAjax = false;

/** The iframe that we are using to poll */
dwr.engine._outstandingIFrames = [];

/** The xhr object that we are using to poll */
dwr.engine._pollReq = null;

/** How many milliseconds between internal comet polls */
dwr.engine._pollCometInterval = 200;

/** How many times have we re-tried to poll? */
dwr.engine._pollRetries = 0;
dwr.engine._maxPollRetries = 0;

/** Do we do a document.reload if we get a text/html reply? */
dwr.engine._textHtmlHandler = null;

/** If you wish to send custom headers with every request */
dwr.engine._headers = null;

/** If you wish to send extra custom request parameters with each request */
dwr.engine._parameters = null;

/** Undocumented interceptors - do not use */
dwr.engine._postSeperator = "\n";
dwr.engine._defaultInterceptor = function(data) { return data; };
dwr.engine._urlRewriteHandler = dwr.engine._defaultInterceptor;
dwr.engine._contentRewriteHandler = dwr.engine._defaultInterceptor;
dwr.engine._replyRewriteHandler = dwr.engine._defaultInterceptor;

/** Batch ids allow us to know which batch the server is answering */
dwr.engine._nextBatchId = 0;

/** A list of the properties that need merging from calls to a batch */
dwr.engine._propnames = [ "rpcType", "httpMethod", "async", "timeout", "errorHandler", "warningHandler", "textHtmlHandler" ];

/** Do we stream, or can be hacked to do so? */
dwr.engine._partialResponseNo = 0;
dwr.engine._partialResponseYes = 1;
dwr.engine._partialResponseFlush = 2;

/** Is this page in the process of unloading? */
dwr.engine._unloading = false;

/**
 * @private Send a request. Called by the Javascript interface stub
 * @param path part of URL after the host and before the exec bit without leading or trailing /s
 * @param scriptName The class to execute
 * @param methodName The method on said class to execute
 * @param func The callback function to which any returned data should be passed
 *       if this is null, any returned data will be ignored
 * @param vararg_params The parameters to pass to the above class
 */
dwr.engine._execute = function(path, scriptName, methodName, vararg_params) {
  var singleShot = false;
  if (dwr.engine._batch == null) {
    dwr.engine.beginBatch();
    singleShot = true;
  }
  var batch = dwr.engine._batch;
  // To make them easy to manipulate we copy the arguments into an args array
  var args = [];
  for (var i = 0; i < arguments.length - 3; i++) {
    args[i] = arguments[i + 3];
  }
  // All the paths MUST be to the same servlet
  if (batch.path == null) {
    batch.path = path;
  }
  else {
    if (batch.path != path) {
      dwr.engine._handleError(batch, { name:"dwr.engine.multipleServlets", message:"Can't batch requests to multiple DWR Servlets." });
      return;
    }
  }
  // From the other params, work out which is the function (or object with
  // call meta-data) and which is the call parameters
  var callData;
  var lastArg = args[args.length - 1];
  if (typeof lastArg == "function" || lastArg == null) callData = { callback:args.pop() };
  else callData = args.pop();

  // Merge from the callData into the batch
  dwr.engine._mergeBatch(batch, callData);
  batch.handlers[batch.map.callCount] = {
    exceptionHandler:callData.exceptionHandler,
    callback:callData.callback
  };

  // Copy to the map the things that need serializing
  var prefix = "c" + batch.map.callCount + "-";
  batch.map[prefix + "scriptName"] = scriptName;
  batch.map[prefix + "methodName"] = methodName;
  batch.map[prefix + "id"] = batch.map.callCount;
  for (i = 0; i < args.length; i++) {
    dwr.engine._serializeAll(batch, [], args[i], prefix + "param" + i);
  }

  // Now we have finished remembering the call, we incr the call count
  batch.map.callCount++;
  if (singleShot) dwr.engine.endBatch();
};

/** @private Poll the server to see if there is any data waiting */
dwr.engine._poll = function() {
  if (!dwr.engine._activeReverseAjax) return;

  var batch = dwr.engine._createBatch();
  batch.map.id = 0; // TODO: Do we need this??
  batch.map.callCount = 1;
  batch.isPoll = true;
  if (dwr.engine._pollWithXhr == "true") {
    batch.rpcType = dwr.engine.XMLHttpRequest;
    batch.map.partialResponse = dwr.engine._partialResponseNo;
  }
  else {
    if (navigator.userAgent.indexOf("Gecko/") != -1) {
      batch.rpcType = dwr.engine.XMLHttpRequest;
      batch.map.partialResponse = dwr.engine._partialResponseYes;
    }
    else {
      batch.rpcType = dwr.engine.XMLHttpRequest;
      batch.map.partialResponse = dwr.engine._partialResponseNo;
    }
  }
  batch.httpMethod = "POST";
  batch.async = true;
  batch.timeout = 0;
  batch.path = dwr.engine._defaultPath;
  batch.preHooks = [];
  batch.postHooks = [];
  batch.errorHandler = dwr.engine._pollErrorHandler;
  batch.warningHandler = dwr.engine._pollErrorHandler;
  batch.handlers[0] = {
    callback:function(pause) {
      dwr.engine._pollRetries = 0;
      setTimeout(dwr.engine._poll, pause);
    }
  };

  // Send the data
  dwr.engine._sendData(batch);
  if (batch.rpcType == dwr.engine.XMLHttpRequest && batch.map.partialResponse == dwr.engine._partialResponseYes) {
    dwr.engine._checkCometPoll();
  }
};

/** Try to recover from polling errors */
dwr.engine._pollErrorHandler = function(msg, ex) {
  // if anything goes wrong then just silently try again (up to 3x) after 10s
  dwr.engine._pollRetries++;
  dwr.engine._debug("Reverse Ajax poll failed (pollRetries=" + dwr.engine._pollRetries + "): " + ex.name + " : " + ex.message);
  if (dwr.engine._pollRetries < dwr.engine._maxPollRetries) {
    setTimeout(dwr.engine._poll, 10000);
  }
  else {
    dwr.engine._activeReverseAjax = false;
    dwr.engine._debug("Giving up.");
  }
};

/** @private Generate a new standard batch */
dwr.engine._createBatch = function() {
  var batch = {
    map:{
      callCount:0,
      page:window.location.pathname + window.location.search,
      httpSessionId:dwr.engine._getJSessionId(),
      scriptSessionId:dwr.engine._getScriptSessionId()
    },
    charsProcessed:0, paramCount:0,
    parameters:{}, headers:{},
    isPoll:false, handlers:{}, preHooks:[], postHooks:[],
    rpcType:dwr.engine._rpcType,
    httpMethod:dwr.engine._httpMethod,
    async:dwr.engine._async,
    timeout:dwr.engine._timeout,
    errorHandler:dwr.engine._errorHandler,
    warningHandler:dwr.engine._warningHandler,
    textHtmlHandler:dwr.engine._textHtmlHandler
  };
  if (dwr.engine._preHook) batch.preHooks.push(dwr.engine._preHook);
  if (dwr.engine._postHook) batch.postHooks.push(dwr.engine._postHook);
  var propname, data;
  if (dwr.engine._headers) {
    for (propname in dwr.engine._headers) {
      data = dwr.engine._headers[propname];
      if (typeof data != "function") batch.headers[propname] = data;
    }
  }
  if (dwr.engine._parameters) {
    for (propname in dwr.engine._parameters) {
      data = dwr.engine._parameters[propname];
      if (typeof data != "function") batch.parameters[propname] = data;
    }
  }
  return batch;
};

/** @private Take further options and merge them into */
dwr.engine._mergeBatch = function(batch, overrides) {
  var propname, data;
  for (var i = 0; i < dwr.engine._propnames.length; i++) {
    propname = dwr.engine._propnames[i];
    if (overrides[propname] != null) batch[propname] = overrides[propname];
  }
  if (overrides.preHook != null) batch.preHooks.unshift(overrides.preHook);
  if (overrides.postHook != null) batch.postHooks.push(overrides.postHook);
  if (overrides.headers) {
    for (propname in overrides.headers) {
      data = overrides.headers[propname];
      if (typeof data != "function") batch.headers[propname] = data;
    }
  }
  if (overrides.parameters) {
    for (propname in overrides.parameters) {
      data = overrides.parameters[propname];
      if (typeof data != "function") batch.map["p-" + propname] = "" + data;
    }
  }
};

/** @private What is our session id? */
dwr.engine._getJSessionId =  function() {
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
    if (cookie.indexOf(dwr.engine._sessionCookieName + "=") == 0) {
      return cookie.substring(dwr.engine._sessionCookieName.length + 1, cookie.length);
    }
  }
  return "";
};

/** @private Check for reverse Ajax activity */
dwr.engine._checkCometPoll = function() {
  for (var i = 0; i < dwr.engine._outstandingIFrames.length; i++) {
    var text = "";
    var iframe = dwr.engine._outstandingIFrames[i];
    try {
      text = dwr.engine._getTextFromCometIFrame(iframe);
    }
    catch (ex) {
      dwr.engine._handleWarning(iframe.batch, ex);
    }
    if (text != "") dwr.engine._processCometResponse(text, iframe.batch);
  }
  if (dwr.engine._pollReq) {
    var req = dwr.engine._pollReq;
    var text = req.responseText;
    if (text != null) dwr.engine._processCometResponse(text, req.batch);
  }

  // If the poll resources are still there, come back again
  if (dwr.engine._outstandingIFrames.length > 0 || dwr.engine._pollReq) {
    setTimeout(dwr.engine._checkCometPoll, dwr.engine._pollCometInterval);
  }
};

/** @private Extract the whole (executed an all) text from the current iframe */
dwr.engine._getTextFromCometIFrame = function(frameEle) {
  var body = frameEle.contentWindow.document.body;
  if (body == null) return "";
  var text = body.innerHTML;
  // We need to prevent IE from stripping line feeds
  if (text.indexOf("<PRE>") == 0 || text.indexOf("<pre>") == 0) {
    text = text.substring(5, text.length - 7);
  }
  return text;
};

/** @private Some more text might have come in, test and execute the new stuff */
dwr.engine._processCometResponse = function(response, batch) {
  if (batch.charsProcessed == response.length) return;
  if (response.length == 0) {
    batch.charsProcessed = 0;
    return;
  }

  var firstStartTag = response.indexOf("//#DWR-START#", batch.charsProcessed);
  if (firstStartTag == -1) {
    // dwr.engine._debug("No start tag (search from " + batch.charsProcessed + "). skipping '" + response.substring(batch.charsProcessed) + "'");
    batch.charsProcessed = response.length;
    return;
  }
  // if (firstStartTag > 0) {
  //   dwr.engine._debug("Start tag not at start (search from " + batch.charsProcessed + "). skipping '" + response.substring(batch.charsProcessed, firstStartTag) + "'");
  // }

  var lastEndTag = response.lastIndexOf("//#DWR-END#");
  if (lastEndTag == -1) {
    // dwr.engine._debug("No end tag. unchanged charsProcessed=" + batch.charsProcessed);
    return;
  }

  // Skip the end tag too for next time, remembering CR and LF
  if (response.charCodeAt(lastEndTag + 11) == 13 && response.charCodeAt(lastEndTag + 12) == 10) {
    batch.charsProcessed = lastEndTag + 13;
  }
  else {
    batch.charsProcessed = lastEndTag + 11;
  }

  var exec = response.substring(firstStartTag + 13, lastEndTag);

  dwr.engine._receivedBatch = batch;
  dwr.engine._eval(exec);
  dwr.engine._receivedBatch = null;
};

/** @private Actually send the block of data in the batch object. */
dwr.engine._sendData = function(batch) {
  batch.map.batchId = dwr.engine._nextBatchId;
  dwr.engine._nextBatchId++;
  dwr.engine._batches[batch.map.batchId] = batch;
  dwr.engine._batchesLength++;
  batch.completed = false;

  for (var i = 0; i < batch.preHooks.length; i++) {
    batch.preHooks[i]();
  }
  batch.preHooks = null;
  // Set a timeout
  if (batch.timeout && batch.timeout != 0) {
    batch.timeoutId = setTimeout(function() { dwr.engine._abortRequest(batch); }, batch.timeout);
  }
  // Get setup for XMLHttpRequest if possible
  if (batch.rpcType == dwr.engine.XMLHttpRequest) {
    if (window.XMLHttpRequest) {
      batch.req = new XMLHttpRequest();
    }
    // IE5 for the mac claims to support window.ActiveXObject, but throws an error when it's used
    else if (window.ActiveXObject && !(navigator.userAgent.indexOf("Mac") >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
      batch.req = dwr.engine._newActiveXObject(dwr.engine._XMLHTTP);
    }
  }

  var prop, request;
  if (batch.req) {
    // Proceed using XMLHttpRequest
    if (batch.async) {
      batch.req.onreadystatechange = function() {
        if (typeof dwr != 'undefined') dwr.engine._stateChange(batch);
      };
    }
    // If we're polling, record this for monitoring
    if (batch.isPoll) {
      dwr.engine._pollReq = batch.req;
      // In IE XHR is an ActiveX control so you can't augment it like this
      if (!(document.all && !window.opera)) batch.req.batch = batch;
    }
    // Workaround for Safari 1.x POST bug
    var indexSafari = navigator.userAgent.indexOf("Safari/");
    if (indexSafari >= 0) {
      var version = navigator.userAgent.substring(indexSafari + 7);
      if (parseInt(version, 10) < 400) {
        if (dwr.engine._allowGetForSafariButMakeForgeryEasier == "true") batch.httpMethod = "GET";
        else dwr.engine._handleWarning(batch, { name:"dwr.engine.oldSafari", message:"Safari GET support disabled. See getahead.org/dwr/server/servlet and allowGetForSafariButMakeForgeryEasier." });
      }
    }
    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
    request = dwr.engine._constructRequest(batch);
    try {
      batch.req.open(batch.httpMethod, request.url, batch.async);
      try {
        for (prop in batch.headers) {
          var value = batch.headers[prop];
          if (typeof value == "string") batch.req.setRequestHeader(prop, value);
        }
        if (!batch.headers["Content-Type"]) batch.req.setRequestHeader("Content-Type", "text/plain");
      }
      catch (ex) {
        dwr.engine._handleWarning(batch, ex);
      }
      batch.req.send(request.body);
      if (!batch.async) dwr.engine._stateChange(batch);
    }
    catch (ex) {
      dwr.engine._handleError(batch, ex);
    }
  }
  else if (batch.rpcType != dwr.engine.ScriptTag) {
    var idname = batch.isPoll ? "dwr-if-poll-" + batch.map.batchId : "dwr-if-" + batch.map.batchId;
    // Removed htmlfile implementation. Don't expect it to return before v3
    batch.div = document.createElement("div");
    // Add the div to the document first, otherwise IE 6 will ignore onload handler.
    document.body.appendChild(batch.div);
    batch.div.innerHTML = "<iframe src='javascript:void(0)' frameborder='0' style='width:0px;height:0px;border:0;' id='" + idname + "' name='" + idname + "' onload='dwr.engine._iframeLoadingComplete (" + batch.map.batchId + ");'></iframe>";
    batch.document = document;
    batch.iframe = batch.document.getElementById(idname);
    batch.iframe.batch = batch;
    batch.mode = batch.isPoll ? dwr.engine._ModeHtmlPoll : dwr.engine._ModeHtmlCall;
    if (batch.isPoll) dwr.engine._outstandingIFrames.push(batch.iframe);
    request = dwr.engine._constructRequest(batch);
    if (batch.httpMethod == "GET") {
      batch.iframe.setAttribute("src", request.url);
    }
    else {
      batch.form = batch.document.createElement("form");
      batch.form.setAttribute("id", "dwr-form");
      batch.form.setAttribute("action", request.url);
      batch.form.setAttribute("style", "display:none;");
      batch.form.setAttribute("target", idname);
      batch.form.target = idname;
      batch.form.setAttribute("method", batch.httpMethod);
      for (prop in batch.map) {
        var value = batch.map[prop];
        if (typeof value != "function") {
          var formInput = batch.document.createElement("input");
          formInput.setAttribute("type", "hidden");
          formInput.setAttribute("name", prop);
          formInput.setAttribute("value", value);
          batch.form.appendChild(formInput);
        }
      }
      batch.document.body.appendChild(batch.form);
      batch.form.submit();
    }
  }
  else {
    batch.httpMethod = "GET"; // There's no such thing as ScriptTag using POST
    batch.mode = batch.isPoll ? dwr.engine._ModePlainPoll : dwr.engine._ModePlainCall;
    request = dwr.engine._constructRequest(batch);
    batch.script = document.createElement("script");
    batch.script.id = "dwr-st-" + batch.map["c0-id"];
    batch.script.src = request.url;
    document.body.appendChild(batch.script);
  }
};

dwr.engine._ModePlainCall = "/call/plaincall/";
dwr.engine._ModeHtmlCall = "/call/htmlcall/";
dwr.engine._ModePlainPoll = "/call/plainpoll/";
dwr.engine._ModeHtmlPoll = "/call/htmlpoll/";

/** @private Work out what the URL should look like */
dwr.engine._constructRequest = function(batch) {
  // A quick string to help people that use web log analysers
  var request = { url:batch.path + batch.mode, body:null };
  if (batch.isPoll == true) {
    request.url += "ReverseAjax.dwr";
  }
  else if (batch.map.callCount == 1) {
    request.url += batch.map["c0-scriptName"] + "." + batch.map["c0-methodName"] + ".dwr";
  }
  else {
    request.url += "Multiple." + batch.map.callCount + ".dwr";
  }
  // Play nice with url re-writing
  var sessionMatch = location.href.match(/jsessionid=([^?]+)/);
  if (sessionMatch != null) {
    request.url += ";jsessionid=" + sessionMatch[1];
  }

  var prop;
  if (batch.httpMethod == "GET") {
    // Some browsers (Opera/Safari2) seem to fail to convert the callCount value
    // to a string in the loop below so we do it manually here.
    batch.map.callCount = "" + batch.map.callCount;
    request.url += "?";
    for (prop in batch.map) {
      if (typeof batch.map[prop] != "function") {
        request.url += encodeURIComponent(prop) + "=" + encodeURIComponent(batch.map[prop]) + "&";
      }
    }
    request.url = request.url.substring(0, request.url.length - 1);
  }
  else {
    // PERFORMANCE: for iframe mode this is thrown away.
    request.body = "";
    if (document.all && !window.opera) {
      // Use array joining on IE (fastest)
      var buf = [];
      for (prop in batch.map) {
        if (typeof batch.map[prop] != "function") {
          buf.push(prop + "=" + batch.map[prop] + dwr.engine._postSeperator);
        }
      }
      request.body = buf.join("");
    }
    else {
      // Use string concat on other browsers (fastest)
      for (prop in batch.map) {
        if (typeof batch.map[prop] != "function") {
          request.body += prop + "=" + batch.map[prop] + dwr.engine._postSeperator;
        }
      }
    }
    request.body = dwr.engine._contentRewriteHandler(request.body);
  }
  request.url = dwr.engine._urlRewriteHandler(request.url);
  return request;
};

/** @private Called by XMLHttpRequest to indicate that something has happened */
dwr.engine._stateChange = function(batch) {
  var toEval;

  if (batch.completed) {
    dwr.engine._debug("Error: _stateChange() with batch.completed");
    return;
  }

  var req = batch.req;
  try {
    if (req.readyState != 4) return;
  }
  catch (ex) {
    dwr.engine._handleWarning(batch, ex);
    // It's broken - clear up and forget this call
    dwr.engine._clearUp(batch);
    return;
  }

  if (dwr.engine._unloading) {
    dwr.engine._debug("Ignoring reply from server as page is unloading.");
    return;
  }
  
  try {
    var reply = req.responseText;
    reply = dwr.engine._replyRewriteHandler(reply);
    var status = req.status; // causes Mozilla to except on page moves

    if (reply == null || reply == "") {
      dwr.engine._handleWarning(batch, { name:"dwr.engine.missingData", message:"No data received from server" });
    }
    else if (status != 200) {
      dwr.engine._handleError(batch, { name:"dwr.engine.http." + status, message:req.statusText });
    }
    else {
      var contentType = req.getResponseHeader("Content-Type");
      if (!contentType.match(/^text\/plain/) && !contentType.match(/^text\/javascript/)) {
        if (contentType.match(/^text\/html/) && typeof batch.textHtmlHandler == "function") {
          batch.textHtmlHandler({ status:status, responseText:reply, contentType:contentType });
        }
        else {
          dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidMimeType", message:"Invalid content type: '" + contentType + "'" });
        }
      }
      else {
        // Comet replies might have already partially executed
        if (batch.isPoll && batch.map.partialResponse == dwr.engine._partialResponseYes) {
          dwr.engine._processCometResponse(reply, batch);
        }
        else {
          if (reply.search("//#DWR") == -1) {
            dwr.engine._handleWarning(batch, { name:"dwr.engine.invalidReply", message:"Invalid reply from server" });
          }
          else {
            toEval = reply;
          }
        }
      }
    }
  }
  catch (ex) {
    dwr.engine._handleWarning(batch, ex);
  }

  dwr.engine._callPostHooks(batch);

  // Outside of the try/catch so errors propogate normally:
  dwr.engine._receivedBatch = batch;
  if (toEval != null) toEval = toEval.replace(dwr.engine._scriptTagProtection, "");
  dwr.engine._eval(toEval);
  dwr.engine._receivedBatch = null;
  dwr.engine._validateBatch(batch);
  if (!batch.completed) dwr.engine._clearUp(batch);
};

/**
 * @private This function is invoked when a batch reply is received.
 * It checks that there is a response for every call in the batch. Otherwise,
 * an error will be signaled (a call without a response indicates that the 
 * server failed to send complete batch response). 
 */
dwr.engine._validateBatch = function(batch) {
  // If some call left unreplied, report an error.
  if (!batch.completed) {
    for (var i = 0; i < batch.map.callCount; i++) {
      if (batch.handlers[i] != null) {
        dwr.engine._handleWarning(batch, { name:"dwr.engine.incompleteReply", message:"Incomplete reply from server" });
        break;
      }
    }
  }
}

/** @private Called from iframe onload, check batch using batch-id */
dwr.engine._iframeLoadingComplete = function(batchId) {
  // dwr.engine._checkCometPoll();
  var batch = dwr.engine._batches[batchId];
  if (batch) dwr.engine._validateBatch(batch);
}

/** @private Called by the server: Execute a callback */
dwr.engine._remoteHandleCallback = function(batchId, callId, reply) {
  var batch = dwr.engine._batches[batchId];
  if (batch == null) {
    dwr.engine._debug("Warning: batch == null in remoteHandleCallback for batchId=" + batchId, true);
    return;
  }
  // Error handlers inside here indicate an error that is nothing to do
  // with DWR so we handle them differently.
  try {
    var handlers = batch.handlers[callId];
    batch.handlers[callId] = null;
    if (!handlers) {
      dwr.engine._debug("Warning: Missing handlers. callId=" + callId, true);
    }
    else if (typeof handlers.callback == "function") handlers.callback(reply);
  }
  catch (ex) {
    dwr.engine._handleError(batch, ex);
  }
};

/** @private Called by the server: Handle an exception for a call */
dwr.engine._remoteHandleException = function(batchId, callId, ex) {
  var batch = dwr.engine._batches[batchId];
  if (batch == null) { dwr.engine._debug("Warning: null batch in remoteHandleException", true); return; }
  var handlers = batch.handlers[callId];
  batch.handlers[callId] = null;
  if (handlers == null) { dwr.engine._debug("Warning: null handlers in remoteHandleException", true); return; }
  if (ex.message == undefined) ex.message = "";
  if (typeof handlers.exceptionHandler == "function") handlers.exceptionHandler(ex.message, ex);
  else if (typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
};

/** @private Called by the server: The whole batch is broken */
dwr.engine._remoteHandleBatchException = function(ex, batchId) {
  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
  if (searchBatch) {
    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
  }
  if (ex.message == undefined) ex.message = "";
  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
  if (searchBatch) {
    dwr.engine._receivedBatch = null;
    dwr.engine._clearUp(dwr.engine._batches[batchId]);
  }
};

/** @private Called by the server: Reverse ajax should not be used */
dwr.engine._remotePollCometDisabled = function(ex, batchId) {
  dwr.engine.setActiveReverseAjax(false);
  var searchBatch = (dwr.engine._receivedBatch == null && batchId != null);
  if (searchBatch) {
    dwr.engine._receivedBatch = dwr.engine._batches[batchId];
  }
  if (ex.message == undefined) ex.message = "";
  dwr.engine._handleError(dwr.engine._receivedBatch, ex);
  if (searchBatch) {
    dwr.engine._receivedBatch = null;
    dwr.engine._clearUp(dwr.engine._batches[batchId]);
  }
};

/** @private Called by the server: An IFrame reply is about to start */
dwr.engine._remoteBeginIFrameResponse = function(iframe, batchId) {
  if (iframe != null) dwr.engine._receivedBatch = iframe.batch;
  dwr.engine._callPostHooks(dwr.engine._receivedBatch);
};

/** @private Called by the server: An IFrame reply is just completing */
dwr.engine._remoteEndIFrameResponse = function(batchId) {
  dwr.engine._clearUp(dwr.engine._receivedBatch);
  dwr.engine._receivedBatch = null;
};

/** @private This is a hack to make the context be this window */
dwr.engine._eval = function(script) {
  if (script == null) return null;
  if (script == "") { dwr.engine._debug("Warning: blank script", true); return null; }
  // dwr.engine._debug("Exec: [" + script + "]", true);
  return eval(script);
};

/** @private Called as a result of a request timeout */
dwr.engine._abortRequest = function(batch) {
  if (batch && !batch.completed) {
    dwr.engine._clearUp(batch);
    if (batch.req) batch.req.abort();
    dwr.engine._handleError(batch, { name:"dwr.engine.timeout", message:"Timeout" });
  }
};

/** @private call all the post hooks for a batch */
dwr.engine._callPostHooks = function(batch) {
  if (batch.postHooks) {
    for (var i = 0; i < batch.postHooks.length; i++) {
      batch.postHooks[i]();
    }
    batch.postHooks = null;
  }
};

/** @private A call has finished by whatever means and we need to shut it all down. */
dwr.engine._clearUp = function(batch) {
  if (!batch) { dwr.engine._debug("Warning: null batch in dwr.engine._clearUp()", true); return; }
  if (batch.completed) { dwr.engine._debug("Warning: Double complete", true); return; }

  // IFrame tidyup
  if (batch.div) batch.div.parentNode.removeChild(batch.div);
  if (batch.iframe) {
    // If this is a poll frame then stop comet polling
    for (var i = 0; i < dwr.engine._outstandingIFrames.length; i++) {
      if (dwr.engine._outstandingIFrames[i] == batch.iframe) {
        dwr.engine._outstandingIFrames.splice(i, 1);
      }
    }
    batch.iframe.parentNode.removeChild(batch.iframe);
  }
  if (batch.form) batch.form.parentNode.removeChild(batch.form);

  // XHR tidyup: avoid IE handles increase
  if (batch.req) {
    // If this is a poll frame then stop comet polling
    if (batch.req == dwr.engine._pollReq) dwr.engine._pollReq = null;
    delete batch.req;
  }

  // Timeout tidyup
  if (batch.timeoutId) {
    clearTimeout(batch.timeoutId);
    delete batch.timeoutId;
  }

  if (batch.map && (batch.map.batchId || batch.map.batchId == 0)) {
    delete dwr.engine._batches[batch.map.batchId];
    dwr.engine._batchesLength--;
  }

  batch.completed = true;

  // If there is anything on the queue waiting to go out, then send it.
  // We don't need to check for ordered mode, here because when ordered mode
  // gets turned off, we still process *waiting* batches in an ordered way.
  if (dwr.engine._batchQueue.length != 0) {
    var sendbatch = dwr.engine._batchQueue.shift();
    dwr.engine._sendData(sendbatch);
  }
};

/** @private Abort any XHRs in progress at page unload (solves zombie socket problems in IE). */
dwr.engine._unloader = function() {
  dwr.engine._unloading = true;

  // Empty queue of waiting ordered requests
  dwr.engine._batchQueue.length = 0;

  // Abort any ongoing XHRs and clear their batches
  for (var batchId in dwr.engine._batches) {
    var batch = dwr.engine._batches[batchId];
    // Only process objects that look like batches (avoid prototype additions!)
    if (batch && batch.map) {
      if (batch.req) {
        batch.req.abort();
      }
      dwr.engine._clearUp(batch);
    }
  }
};
// Now register the unload handler
if (window.addEventListener) window.addEventListener('unload', dwr.engine._unloader, false);
else if (window.attachEvent) window.attachEvent('onunload', dwr.engine._unloader);

/** @private Generic error handling routing to save having null checks everywhere */
dwr.engine._handleError = function(batch, ex) {
  if (typeof ex == "string") ex = { name:"unknown", message:ex };
  if (ex.message == null) ex.message = "";
  if (ex.name == null) ex.name = "unknown";
  if (batch && typeof batch.errorHandler == "function") batch.errorHandler(ex.message, ex);
  else if (dwr.engine._errorHandler) dwr.engine._errorHandler(ex.message, ex);
  if (batch) dwr.engine._clearUp(batch);
};

/** @private Generic error handling routing to save having null checks everywhere */
dwr.engine._handleWarning = function(batch, ex) {
  if (typeof ex == "string") ex = { name:"unknown", message:ex };
  if (ex.message == null) ex.message = "";
  if (ex.name == null) ex.name = "unknown";
  if (batch && typeof batch.warningHandler == "function") batch.warningHandler(ex.message, ex);
  else if (dwr.engine._warningHandler) dwr.engine._warningHandler(ex.message, ex);
  if (batch) dwr.engine._clearUp(batch);
};

/**
 * @private Marshall a data item
 * @param batch A map of variables to how they have been marshalled
 * @param referto An array of already marshalled variables to prevent recurrsion
 * @param data The data to be marshalled
 * @param name The name of the data being marshalled
 */
dwr.engine._serializeAll = function(batch, referto, data, name) {
  if (data == null) {
    batch.map[name] = "null:null";
    return;
  }

  switch (typeof data) {
  case "boolean":
    batch.map[name] = "boolean:" + data;
    break;
  case "number":
    batch.map[name] = "number:" + data;
    break;
  case "string":
    batch.map[name] = "string:" + encodeURIComponent(data);
    break;
  case "object":
    if (data instanceof String) batch.map[name] = "String:" + encodeURIComponent(data);
    else if (data instanceof Boolean) batch.map[name] = "Boolean:" + data;
    else if (data instanceof Number) batch.map[name] = "Number:" + data;
    else if (data instanceof Date) batch.map[name] = "Date:" + data.getTime();
    else if (data && data.join) batch.map[name] = dwr.engine._serializeArray(batch, referto, data, name);
    else batch.map[name] = dwr.engine._serializeObject(batch, referto, data, name);
    break;
  case "function":
    // We just ignore functions.
    break;
  default:
    dwr.engine._handleWarning(null, { name:"dwr.engine.unexpectedType", message:"Unexpected type: " + typeof data + ", attempting default converter." });
    batch.map[name] = "default:" + data;
    break;
  }
};

/** @private Have we already converted this object? */
dwr.engine._lookup = function(referto, data, name) {
  var lookup;
  // Can't use a map: getahead.org/ajax/javascript-gotchas
  for (var i = 0; i < referto.length; i++) {
    if (referto[i].data == data) {
      lookup = referto[i];
      break;
    }
  }
  if (lookup) return "reference:" + lookup.name;
  referto.push({ data:data, name:name });
  return null;
};

/** @private Marshall an object */
dwr.engine._serializeObject = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  // This check for an HTML is not complete, but is there a better way?
  // Maybe we should add: data.hasChildNodes typeof "function" == true
  if (data.nodeName && data.nodeType) {
    return dwr.engine._serializeXml(batch, referto, data, name);
  }

  // treat objects as an associative arrays
  var reply = "Object_" + dwr.engine._getObjectClassName(data) + ":{";
  var element;
  for (element in data) {
    if (typeof data[element] != "function") {
      batch.paramCount++;
      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
      dwr.engine._serializeAll(batch, referto, data[element], childName);

      reply += encodeURIComponent(element) + ":reference:" + childName + ", ";
    }
  }

  if (reply.substring(reply.length - 2) == ", ") {
    reply = reply.substring(0, reply.length - 2);
  }
  reply += "}";

  return reply;
};

/** @private Returns the classname of supplied argument obj */
dwr.engine._errorClasses = { "Error":Error, "EvalError":EvalError, "RangeError":RangeError, "ReferenceError":ReferenceError, "SyntaxError":SyntaxError, "TypeError":TypeError, "URIError":URIError };
dwr.engine._getObjectClassName = function(obj) {
  // Try to find the classname by stringifying the object's constructor
  // and extract <class> from "function <class>".
  if (obj && obj.constructor && obj.constructor.toString)
  {
    var str = obj.constructor.toString();
    var regexpmatch = str.match(/function\s+(\w+)/);
    if (regexpmatch && regexpmatch.length == 2) {
      return regexpmatch[1];
    }
  }

  // Now manually test against the core Error classes, as these in some 
  // browsers successfully match to the wrong class in the 
  // Object.toString() test we will do later
  if (obj && obj.constructor) {
	for (var errorname in dwr.engine._errorClasses) {
      if (obj.constructor == dwr.engine._errorClasses[errorname]) return errorname;
    }
  }

  // Try to find the classname by calling Object.toString() on the object
  // and extracting <class> from "[object <class>]"
  if (obj) {
    var str = Object.prototype.toString.call(obj);
    var regexpmatch = str.match(/\[object\s+(\w+)/);
    if (regexpmatch && regexpmatch.length==2) {
      return regexpmatch[1];
    }
  }

  // Supplied argument was probably not an object, but what is better?
  return "Object";
};

/** @private Marshall an object */
dwr.engine._serializeXml = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  var output;
  if (window.XMLSerializer) output = new XMLSerializer().serializeToString(data);
  else if (data.toXml) output = data.toXml;
  else output = data.innerHTML;

  return "XML:" + encodeURIComponent(output);
};

/** @private Marshall an array */
dwr.engine._serializeArray = function(batch, referto, data, name) {
  var ref = dwr.engine._lookup(referto, data, name);
  if (ref) return ref;

  if (document.all && !window.opera) {
    // Use array joining on IE (fastest)
    var buf = ["Array:["];
    for (var i = 0; i < data.length; i++) {
      if (i != 0) buf.push(",");
      batch.paramCount++;
      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
      dwr.engine._serializeAll(batch, referto, data[i], childName);
      buf.push("reference:");
      buf.push(childName);
    }
    buf.push("]");
    reply = buf.join("");
  }
  else {
    // Use string concat on other browsers (fastest)
    var reply = "Array:[";
    for (var i = 0; i < data.length; i++) {
      if (i != 0) reply += ",";
      batch.paramCount++;
      var childName = "c" + dwr.engine._batch.map.callCount + "-e" + batch.paramCount;
      dwr.engine._serializeAll(batch, referto, data[i], childName);
      reply += "reference:";
      reply += childName;
    }
    reply += "]";
  }

  return reply;
};

/** @private Convert an XML string into a DOM object. */
dwr.engine._unserializeDocument = function(xml) {
  var dom;
  if (window.DOMParser) {
    var parser = new DOMParser();
    dom = parser.parseFromString(xml, "text/xml");
    if (!dom.documentElement || dom.documentElement.tagName == "parsererror") {
      var message = dom.documentElement.firstChild.data;
      message += "\n" + dom.documentElement.firstChild.nextSibling.firstChild.data;
      throw message;
    }
    return dom;
  }
  else if (window.ActiveXObject) {
    dom = dwr.engine._newActiveXObject(dwr.engine._DOMDocument);
    dom.loadXML(xml); // What happens on parse fail with IE?
    return dom;
  }
  else {
    var div = document.createElement("div");
    div.innerHTML = xml;
    return div;
  }
};

/** @param axarray An array of strings to attempt to create ActiveX objects from */
dwr.engine._newActiveXObject = function(axarray) {
  var returnValue;  
  for (var i = 0; i < axarray.length; i++) {
    try {
      returnValue = new ActiveXObject(axarray[i]);
      break;
    }
    catch (ex) { /* ignore */ }
  }
  return returnValue;
};

/** @private Used internally when some message needs to get to the programmer */
dwr.engine._debug = function(message, stacktrace) {
  var written = false;
  try {
    if (window.console) {
      if (stacktrace && window.console.trace) window.console.trace();
      window.console.log(message);
      written = true;
    }
    else if (window.opera && window.opera.postError) {
      window.opera.postError(message);
      written = true;
    }
  }
  catch (ex) { /* ignore */ }

  if (!written) {
    var debug = document.getElementById("dwr-debug");
    if (debug) {
      var contents = message + "<br/>" + debug.innerHTML;
      if (contents.length > 2048) contents = contents.substring(0, 2048);
      debug.innerHTML = contents;
    }
  }
};

function top_postNew(){
	window.location.href = WebRoot+"/member/newAPostCategory.jsp";
	/*
	var u=window.location.href;
	var tourl="";
	if(u.indexOf("/solution/")>-1){
		tourl=WebRoot+"/member/newAPostCategory.jsp?type=5";
	}else if(u.indexOf("/request/")>-1){
		tourl=WebRoot+"/member/newAPostCategory.jsp?type=1";
		if(u.indexOf("Reward")>-1){
			tourl=WebRoot+"/member/newAPostCategory.jsp?type=2";			
		}
	}else if(u.indexOf("/service/")>-1){
		tourl=WebRoot+"/member/newAPostCategory.jsp?type=3";
	}else{
		tourl=WebRoot+"/member/newAPostCategory.jsp";
	}
	window.location.href=tourl;
	*/
}
function top_changeLoginStatus(){
	$("loginstatusForm").style.display = "none";
	$("loginstatusText").innerHTML = login_status_text ;
}


var menuEnable;
var defaultMenuEnable=[
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
					[1,1,1,1,1,1,1,1,1,1,1,1,1,1]
				];
function setMenuItem(x,y,v){
	if(menuEnable==null){
		menuEnable=defaultMenuEnable;
	}
	menuEnable[x-1][y-1]=v;
}
function GetBrowser()
{
	var browser = '';
	var agentInfo = navigator.userAgent.toLowerCase();
	if (agentInfo.indexOf("msie") > -1) {
		var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
		var arr = re.exec(agentInfo);
		if (parseInt(RegExp.$1) >= 5.5) {
			browser = 'IE';
		}
	} else if (agentInfo.indexOf("firefox") > -1) {
		browser = 'FF';
	} else if (agentInfo.indexOf("netscape") > -1) {
		var temp1 = agentInfo.split(' ');
		var temp2 = temp1[temp1.length-1].split('/');
		if (parseInt(temp2[1]) >= 7) {
			browser = 'NS';
		}
	} else if (agentInfo.indexOf("gecko") > -1) {
		browser = 'ML';
	} else if (agentInfo.indexOf("opera") > -1) {
		var temp1 = agentInfo.split(' ');
		var temp2 = temp1[0].split('/');
		if (parseInt(temp2[1]) >= 9) {
			browser = 'OPERA';
		}
	}
	return browser;
}


 var currentMenuObj;
 var h;
 var w;
 var l;
 var t;
 var topMar =34;
 var leftMar = 1;
 if(GetBrowser()!="IE"){
 	leftMar = 0;
 }
 var space = 1;
 var isvisible;
 var global = window.document;
 global.fo_currentMenu = null;
 global.fo_shadows = new Array;
function HideMenu(eventobject) 
{
 var eve=eventobject||window.event;
 var mX;
 var mY;
 var vDiv;
 var mDiv;
	if (isvisible == true)
	{
			vDiv = document.getElementById("menuDiv1");
			mX = eve.clientX + document.documentElement.scrollLeft;
			mY = eve.clientY + document.documentElement.scrollTop;			
			if ((mX < parseInt(vDiv.style.left)) || (mX > parseInt(vDiv.style.left)+vDiv.offsetWidth-3) || (mY < parseInt(vDiv.style.top)-3) || (mY > parseInt(vDiv.style.top)+vDiv.offsetHeight-3)){
				vDiv.style.visibility = "hidden";
				isvisible = false;
				try{
					RunAfterHideMenu(eventobject,currentMenuObj);
				}catch(err){
				}				
			}
	}
}
function ShowMenu(vMnuCode,vMnuEvent,tWidth,eventobject,obj,menuNum) {
	var eve=eventobject||window.event;
	try{
		RunAfterHideMenu(eventobject,currentMenuObj);
	}catch(err){
	}
	if(menuEnable==null)menuEnable=defaultMenuEnable;
	currentMenuObj=obj;

	var MenuStr="";
	for(var i=0;i<vMnuCode.length;i++){
		if(vMnuCode[i]=="-"){
				MenuStr+="<div class=\"menuSprItem\"></div>";
		}
		else{
			if(menuEnable[menuNum-1][i]==1)
			{
				MenuStr+="<div class=\"menuItem\" onmouseover='this.className=\"menuItemHover\"' onmouseout='this.className=\"menuItemOut\"' onclick='"+vMnuEvent[i]+"'>"+vMnuCode[i]+"</div>";
			}
			else
			{
				MenuStr+="<div class=\"menuItem_disabled\" onmouseover='this.className=\"menuItemHover_disabled\"' onmouseout='this.className=\"menuItemOut_disabled\"'>"+vMnuCode[i]+"</div>"
			}
		}

	}
    MenuStr= "<div id='submenu' class='popupmenu' style='width:"+tWidth+";' onmouseout='HideMenu(event)'>" + MenuStr+ "</div>";
	 var ePosition = GetAbsoluteLocationEx(obj);
	 l = ePosition.absoluteLeft + leftMar;
	 t = ePosition.absoluteTop + topMar;	

	document.getElementById("menuDiv1").innerHTML = MenuStr;
	document.getElementById("menuDiv1").style.top = t+"px";
	document.getElementById("menuDiv1").style.left = l+"px";
	document.getElementById("menuDiv1").style.visibility = "visible";
	isvisible = true;
	try{
		RunAfterShowMenu(eventobject,currentMenuObj);
	}catch(err){
	}
}



function GetAbsoluteLocationEx(element) 
{ 
    if ( arguments.length != 1 || element == null ) 
    { 
        return null; 
    } 
    var elmt = element; 
    var offsetTop = elmt.offsetTop; 
    var offsetLeft = elmt.offsetLeft; 
    var offsetWidth = elmt.offsetWidth; 
    var offsetHeight = elmt.offsetHeight; 
    while( elmt = elmt.offsetParent ) 
    { 
          // add this judge 
        if ( elmt.style.position == 'absolute' || elmt.style.position == 'relative'  
            || ( elmt.style.overflow != 'visible' && elmt.style.overflow != '' ) ) 
        { 
            break; 
        }  
        offsetTop += elmt.offsetTop; 
        offsetLeft += elmt.offsetLeft; 
    } 
    return { absoluteTop: offsetTop, absoluteLeft: offsetLeft, 
        offsetWidth: offsetWidth, offsetHeight: offsetHeight }; 
} 

/*****************************************************************************************************************************************************/
function RunAfterHideMenu(eventobject,obj){
	obj.className="z2_menu1";
}

function RunAfterShowMenu(eventobject,obj){
	obj.className="z2_menu2";
}

var m1=new Array(member_memberTop_label_assetManagement, member_memberTop_label_tradeManagement, member_memberTop_label_SMS, member_memberTop_label_addressBook, member_memberTop_label_personalSettings,member_memberTop_label_storeset);
var m2=new Array("Post New","Account Recharge");
var m3=new Array("Trading Security", "Forum", "Help");
var m4=new Array("English","中文简体", "香港繁體", "臺灣繁體");
//var m4=new Array("中文简体", "香港繁體", "臺灣繁體");

var e1=new Array("javascript:window.location.href=\""+WebRoot+"/member/assetManagement.jsp\";","javascript:window.location.href=\""+WebRoot+"/member/tradingHome.jsp\";","javascript:window.location.href=\""+WebRoot+"/member/myInternalMes.jsp\";","javascript:window.location.href=\""+WebRoot+"/member/myFriends.jsp\";","javascript:window.location.href=\""+WebRoot+"/member/myPreferences.jsp\";","javascript:window.location.href=\""+WebRoot+"/member/commodity/myShop.jsp\";");
var e2=new Array("","");
var e3=new Array("","","","");
var e4=new Array("javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=en\";", "javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=zh_CN\";", "javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=zh_HK\";", "javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=zh_TW\";");
//var e4=new Array("javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=zh_CN\";", "javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=zh_HK\";", "javascript:window.location.href=\""+WebRoot+"/language.jsp?lang=zh_TW\";");

	function XmlFileReader(xmlFile)
	{
                         var createXMLDom=function(){
                         	if (window.ActiveXObject) 
                         		var xmldoc=new ActiveXObject("Microsoft.XMLDOM");
                         		
                         	else 
                         		if (document.implementation&&document.implementation.createDocument)
                         			var xmldoc=document.implementation.createDocument("","doc",null);
                         	xmldoc.async = false;
                         	xmldoc.preserveWhiteSpace=true;
                         	return xmldoc;
                         }
                         
                         var createXMLHttp=function(){
                         	var xmlHttp;
                         	if (window.ActiveXObject){
                         		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                         	}else{
                         		xmlHttp=new XMLHttpRequest();
                         	}
                         	return xmlHttp;
                         }
                         
                         
                         //------------------------Load XML-----------------------------------------------------//
                         var xmlDom=createXMLDom();
                         try{
                         	xmlDom.load(xmlFile);
                         }catch(e){
                         	var xmlHttp=createXMLHttp();
                         		xmlHttp.onreadystatechange = function(){
                         			if(xmlHttp.readyState == 4){
                         				xmlDom=xmlHttp.responseXML;
                         			}else{
                         				//window.state="XML Loading...";
                         			}
                         		}		
                         		xmlHttp.open("GET",xmlFile,false);
                         		xmlHttp.send(null);
						}

			this.getDoc = function(){
				return xmlDom.documentElement;
			}
	}
	
	function XmlReader(xmlStr)
	{
                         var createXMLDom=function(){
                         	if (window.ActiveXObject) 
                         		var xmldoc=new ActiveXObject("Microsoft.XMLDOM");
                         		
                         	else 
                         		if (document.implementation&&document.implementation.createDocument)
                         			var xmldoc=document.implementation.createDocument("","doc",null);
                         	xmldoc.async = false;
                         	xmldoc.preserveWhiteSpace=true;
                         	return xmldoc;
                         }
                         
                         var createXMLHttp=function(){
                         	var xmlHttp;
                         	if (window.ActiveXObject){
                         		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                         	}else{
                         		xmlHttp=new XMLHttpRequest();
                         	}
                         	return xmlHttp;
                         }
                         
                         
                         //------------------------Load XML-----------------------------------------------------//
                         var xmlDom=createXMLDom();
                         try{
							if(document.all)
							{
								var xmlDom=new ActiveXObject("Microsoft.XMLDOM");
								xmlDom.loadXML(xmlStr);
							}
							else
							{
								xmlDom =  new DOMParser().parseFromString(xmlStr, "text/xml");
							}
                         }catch(e){
						}

			this.getDoc = function(){
				return xmlDom.documentElement;
			}
	}
	function DocUtil(doc)
	{
		 this.doc = doc;
		  this.getAtt=function(pNode,pAttribute){
                                     try{
                                     	return pNode.attributes.getNamedItem(pAttribute).nodeValue;
                                     }catch(e){
                                     	return false;
                                     }
		
			}
		  this.getChildLength = function(pNode)
		  {
			 return this.getChilds(pNode).length;
		 }
		 
		 this.getChilds = function(pNode , tagname)
		 {
			if(pNode == null)
				pNode = this.doc;

			 var ary = new Array();
			  try
			  {
				 for(var i=0;i<pNode.childNodes.length;i++)
				  {
					  if(pNode.childNodes[i].nodeType == 1)
					  {
					  	if(tagname != null)
						{
						  	if(pNode.childNodes[i].tagName == tagname);
							  	ary.push(pNode.childNodes[i]);
						}
						else
							ary.push(pNode.childNodes[i]);	
					  }
				  }
			  }
			  catch(err)
			  {
				 return  new Array();
			  }
			 return ary;
		 }

		 this.getChildById = function(pNode,id)
		 {
			var childs = this.getChilds(pNode);
			for(var i=0;i<childs.length;i++)
			{
				var nid =this.getAtt(childs[i] , "id");
				if(nid == id)
				{
					return childs[i];
				}
			}
			return null;
		}
		
		this.getChildsByTagName = function(pNode,tagName)
		{
			var childs = this.getChilds(pNode);
			var ary = new Array();
			for(var i=0;i<childs.length;i++)
			{
				if(childs[i].tagName == tagName)
				{
					ary.push(childs[i]);
				}
			}
			return ary;
		}

		this.getChildsById = function(pNode,id)
		{
			return this.getChilds(this.getChildById(pNode, id));
		}
	}

	
	var filepath = WebRoot+"/tag/moretopic.xml";
	
			function switchMoretopicIcon(imgId)
			{
				switchIcon(imgId , 'images/icon-add.gif?v=201007121651' , 'images/icon-minus.gif?v=201007121651' , 'moretopic');
			
			}
			function switchIcon(imgId , img1 , img2 , switchDiv)
			{
				try
				{
					document.getElementById(imgId).src = document.getElementById(imgId).src.indexOf(img1)>-1 ? img2 : img1;	
					//document.getElementById(switchDiv).style.display = document.getElementById(imgId).src.indexOf(img1)>-1 ? "none" : "";
					if(document.getElementById(imgId).src.indexOf(img1)>-1)
					{
						hidden(switchDiv , "moretopic_mc");
					}
					else
					{
						show(switchDiv , "moretopic_mc");
					}
				}
				catch (err)
				{}
			}

			function selectMoretopic(node){
				var menu_index = node.getAttribute("menu_index");
				var menu_count = node.getAttribute("menu_count");
					menu_index = menu_index*1;
					menu_count = menu_count*1;
				//selected
					if(menu_index == 1)
					{
						//top
						node.className = 'Common_Moretopic_LeftMenu_ItemSelectedTop';
					}
					else
					if(menu_index == menu_count)
					{
						//bottom
						node.className = 'Common_Moretopic_LeftMenu_ItemSelectedBottom';
					}
					else
					{
						//middle
						node.className = 'Common_Moretopic_LeftMenu_ItemSelectedMiddle';
					}
				
			}
		//-------------------------Read XML----------------------------------//
			/*
			var _CurObj=null;
	       var fileReader = new XmlFileReader(filepath);
                      var fileDoc = fileReader.getDoc();
                      var docUtil = new DocUtil(fileDoc);
                      
                      var rootChilds = docUtil.getChildsByTagName(null , "item");
                      var rootChildLen = rootChilds.length;

                      var currentParentTagID = 0;
                for(var i=0;i<rootChildLen;i++)
                {
                      	var item = rootChilds[i];

                      	var itemDiv = document.createElement("DIV");
                      	itemDiv.innerHTML = docUtil.getAtt( item , "name");
						itemDiv.setAttribute("menu_index" , i+1 );
						itemDiv.setAttribute("menu_count" , rootChildLen );
			
	                    (
	                      		function (item , obj)
	                      		{
	                      					obj.onclick = function()
	                      					{
	                      						if(_CurObj!=null)
		                      						_CurObj.className = "Common_Moretopic_LeftMenu_ItemDiselected";
	                      						_CurObj=this;
	                      						var id = docUtil.getAtt(item , "id");
	                      						currentParentTagID = id;
	                      						var flag = "2"; // default: 24 hours
												showTag(id , flag);
												selectMoretopic(this);
	                      					 }
	                      		}
						)(item,itemDiv);

						if(i == 0 )
							itemDiv.onclick();
			
						itemDiv.className ="Common_Moretopic_LeftMenu_ItemDiselected";
                       	document.getElementById("listU").appendChild(itemDiv);
                     
           		}
           		
           		
           		var randomChilds =  docUtil.getChilds(docUtil.getChildsByTagName(null , "random")[0]);
           		
           		for(var i=0;i<randomChilds.length;i++)
                {
                	var item = randomChilds[i];
                	
                	var itemSpan = document.createElement("SPAN");
                		itemSpan.className = "Common_Moretopic_RandomTag";
                		itemSpan.innerHTML = docUtil.getAtt( item , "name");
                		
                		document.getElementById("randomTag").appendChild(itemSpan);
                }	
             */   	
            function changeTagType(flag , obj)
			{
					document.getElementById("tagTitle").innerHTML = obj.innerHTML;
                    showTag(currentParentTagID , flag);
            }
                       	
            function showTag(parentId , flag)
            {
                flag+="";
				document.getElementById("moretopic_childrens").innerHTML = "";
				document.getElementById("moretopic_childrens").style.height = ((rootChildLen-1) * 30) + "px";
				
					  var childs = docUtil.getChildsById(null , parentId);
					 
                  		  for(var i=0;i<childs.length;i++)
              			  {
							  var myflag = docUtil.getAtt(childs[i] , "flag");
						 		
                 				  if(myflag != flag)
                 				 	 continue;

                 				  var detailDiv = document.createElement("DIV");
                     				  detailDiv.innerHTML = docUtil.getAtt(childs[i] , "name");
                 				  var ishot = docUtil.getAtt(childs[i] , "ishot");
                     				  if(ishot == "false")								  
                     				  	detailDiv.className = "Common_Moretopic_Tag";
                     				  else
                     				  	detailDiv.className = "Common_Moretopic_HotTag";

                           		document.getElementById("moretopic_childrens").appendChild(detailDiv);
                           }
			}
			//--------------------Read XML end--------------------------//
			

			//----------------------Div running-------------------------//
				function $(d){return document.getElementById(d);}
				/*
				var vStep = 20;
				var vSpeed = 10;
				var maxHeight =  ((rootChildLen+1) * 30);
				*/
				function show(objid, contentid , x){
				   if(x == null)
				  	 x = 0;
				    
				    $(objid).style.display="block";
				    if(x + vStep >=maxHeight)
				    {
					    $(objid).style.height = maxHeight+"px";
					    $(contentid).style.display="";
					    return ;
				    }
				    else
				    {
					    x +=vStep;
					    $(objid).style.height = x+"px";
					    setTimeout("show('"+objid+"' , '"+contentid+"' , "+ x +")" , vSpeed);
				    }
				}
				
				function hidden(objid , contentid , x){
				   if(x == null)
				   {
					   x = maxHeight;
					    $(contentid).style.display="none";
				   }
				
				    if(x - vStep <=0 )
				    {
					   $(objid).style.height = "0px";
					    return ;
				    }
				    else
				    {
					    x -=vStep;
					    $(objid).style.height = x+"px";
					    setTimeout("hidden('"+objid+"' , '"+contentid+"'  , "+ x +")" , vSpeed);
				    }
				}
				//----------------------Div running end-------------------------//


var _pop;
	try
	{
		_pop = popuper;
	}
	catch(err)
	{	
		try
		{
			_pop = popupPage == undefined ? null : popupPage;
		}catch(err){}
	}

//---------------Popup upload file----------------------//
	//var uploadFileType = "";
	function popup_uploadfile(uploadListPanel , uploadList , uploadFileType)
	{
		_pop.showPage(WebRoot+'/member/shared/uploadFile.jsp?fileType='+uploadFileType+'&parentUrl='+encodeURIComponent(parent.location.href),"","upload_callback('"+uploadListPanel+"' , '"+uploadList+"' , '"+uploadFileType+"')","","conifrmRemoveFiles('"+uploadListPanel+"' , '"+uploadList+"' , '"+uploadFileType+"')");
	}
	
	function upload_callback(uploadListPanel , uploadList ,uploadFileType)
	{
		var data = _pop.getCallBackXMLData();
		
		var nary = data.names == "" ? new Array() : data.names.split(",");
		var iary = data.indexs == "" ? new Array() : data.indexs.split(",");
		var sary = data.sizes == "" ? new Array() : data.sizes.split(",");
		updateFileList(uploadListPanel , uploadList , uploadFileType , nary , iary , sary);
	} 
	
	function filelist_onchange()
	{
		
	}
	
	function updateFileList(uploadListPanel , uploadList , uploadFileType , nary , iary , sary)
	{
		var inhtml = "";
		if(nary.length >0)
		{	
			inhtml += "<table style=\"width:315px;\"> ";
			inhtml += "<tr><td colspan=3 style='line-height:25px;'>新增附件</td></tr> ";
			for(var i=0;i<nary.length;i++)
			{
				if(nary[i] == "")continue;
				
				inhtml += "		<tr> ";
				inhtml += "			<td style=\"width:200px;\"><img src='"+staticServer+"/images/icon-clip.gif' />"+nary[i].getSubstring(20,'...')+"</td> ";
				inhtml += "			<td>"+ (sary == null ? "0" : sary[i].currencyValue())+"K </td> ";
				inhtml += "			<td><a href=\"javascript:void(0);\" onclick=\"removeFile('"+uploadListPanel+"' , '"+uploadList+"' , '"+uploadFileType+"','"+iary[i]+"')\"><span class=\"Font_Link_Underline\">"+common_label_delete+"</span></a></td> ";
				inhtml += "		</tr> ";
			
			}
			inhtml += "</table> ";
		}

		$(uploadListPanel).style.display = nary.length >0 ? "" : "none";
		$(uploadList).innerHTML=inhtml;
		
		try
		{
			filelist_onchange(nary.length);
		}catch(err){}
	}
	
	var _uploadFileType = "";
	var _uploadListPanel = "";
	var _uploadList = "";
	function conifrmRemoveFiles(uploadListPanel , uploadList , uploadFileType)
	{
		_uploadFileType = uploadFileType;
		_uploadListPanel = uploadListPanel;
		_uploadList = uploadList;
		//if(_haduploadsize > 0){
		///	_pop.showDialog("关闭将会遗失已上传数据，您还要继续吗？","","确认 | 取消","sendRPC_delete('all')");
		//}
	}
	
	function removeFile(uploadListPanel , uploadList ,uploadFileType,fileIndex)
	{
		_uploadFileType = uploadFileType;
		_uploadListPanel = uploadListPanel;
		_uploadList = uploadList;
		_pop.showDialog("确认是否删除文件","","确认 | 取消","sendRPC_delete("+fileIndex+")");
	}
	
	  function sendRPC_delete( delindex)
	  {
		var rpcd = new RPCData();
		rpcd.reqData = "<Type>deleteFilesInMemory</Type><Label>";
        rpcd.reqData += "<filetype>"+_uploadFileType+"</filetype>";
        rpcd.reqData += "<index>"+delindex+"</index>";
        rpcd.reqData += "</Label>";
        rpcd.rpcPath = "ATTACHMENT_ACTION";
	    rpcd.rpcCallback = "getFileList_callback(data)";  //update file list
	    rpcd.vars.push(_uploadFileType);
	    rpcd.vars.push(_uploadListPanel);
		rpcd.vars.push(_uploadList);
	    callRPC(rpcd);
      }
      
      
      var _objID = "";
      function getLastOfferBySellerID(buyingID,sellerID,objID,callbackevent){
      		_objID = objID;
      		var rpcd = new RPCData();
			rpcd.reqData = "<Type>getLastOfferHTML</Type><Label>";
	        rpcd.reqData += "<sellerID>"+sellerID+"</sellerID>";
	        rpcd.reqData += "<buyingID>"+buyingID+"</buyingID>";
	        rpcd.reqData += "</Label>";
	        rpcd.rpcPath = "BUY_STANDARD_ACTION";
		    rpcd.rpcCallback = "getLastOfferBySellerID_callback(data)";
		    rpcd.vars.push(callbackevent);
		    callRPC(rpcd);
      
      }
      
      function getLastOfferBySellerID_callback(data,rpcd){
       	var r = XMLTools.parseData(data);
       	if(r.isSucceed){
       	
       	   $(_objID).innerHTML =  r.getString("lastOfferHtml");
       	}
       	 try{
       	   	eval(rpcd.vars[0]);
       	  }catch(err){
       	 }
       	
      
      }
      
      
    function getCacheFileList(uploadListPanel , uploadList , uploadFileType)
	{   
		   	var rpcd = new RPCData();
			rpcd.reqData = "<Type>getFilesInMemory</Type><Label>";
	        rpcd.reqData += "<filetype>"+uploadFileType+"</filetype>";
	        rpcd.reqData += "</Label>";
	        rpcd.rpcPath = "ATTACHMENT_ACTION";
		    rpcd.rpcCallback = "getFileList_callback(data)";
		    rpcd.vars.push(uploadFileType);
		    rpcd.vars.push(uploadListPanel);
		    rpcd.vars.push(uploadList);
		    callRPC(rpcd);
	 }
      
      function getFileList_callback(data , rpcd)
      {
        var r = XMLTools.parseData(data);
		if( r.isSucceed )
		{
			var fileary = new Array();
			var valary = new Array();
			var sizeary = new Array();
			var datas = r.getDatas("List/fileDtl");
			
			for(var i=0;i<datas.length;i++)
			{
				var record = datas[i];
				fileary.push(record.fileName);
				valary.push(record.fileIndex);
				sizeary.push(record.fileSize);
			}
			updateFileList(rpcd.vars[1] , rpcd.vars[2] , rpcd.vars[0] , fileary , valary , sizeary);
		}
		else
		{
			_pop.showMsg( r.getString(""),'','',0);
		}
      }
      
      
      
  //--------------------------Exist Attachment------------------------------------------//    
    //update post use , delete file only save in a jsvar
    var delExistFileIDs = "";
    var paramsAry = new Array();
    function showExistFileList(uploadListPanel , uploadList , uploadFileType , nary , iary , sary ,canDel)
	{
		if(canDel == null) canDel = true;
		
		var inhtml = "";
		paramsAry.push(uploadListPanel);
		paramsAry.push(uploadList);
		paramsAry.push(uploadFileType);
		paramsAry.push(nary);
		paramsAry.push(iary);
		paramsAry.push(sary);
		paramsAry.push(canDel);
		
		var count = 0;
		if(nary.length >0)
		{	
			existFileAry = nary;
			inhtml += "<table style=\"width:315px;\"> ";
			inhtml += "<tr><td colspan=3 style='line-height:25px;'>"+common_label_attachment_old+"</td></tr> ";
			for(var i=0;i<nary.length;i++)
			{
				if(nary[i] == null || nary[i] == "" || nary[i] == "null" || checkHasDelFile(iary[i]))continue;
				inhtml += "		<tr> ";
				inhtml += "			<td style=\"width:200px;\"><img src='"+staticServer+"/images/icon-clip.gif' />"+nary[i].getSubstring(20,'...')+"</td> ";
				inhtml += "			<td>"+ (sary[i] == null ? "0" : sary[i].currencyValue())+"K </td> ";
				inhtml += "			<td>"+ (canDel ? "<a href=\"javascript:confirmRemoveExistFile("+i+" , "+iary[i]+")\"><span class=\"Font_Link_Underline\">"+common_label_delete+"</span></a>" : "&nbsp;") +"</td> ";
				inhtml += "		</tr> ";
				count++;
			}
			inhtml += "</table> ";
		}

		$(uploadListPanel).style.display = count >0 ? "" : "none";
		$(uploadList).innerHTML=inhtml;
	}
	
	function checkHasDelFile(fid)
	{
		if(delExistFileIDs == "") return false;
		
		var delIds = delExistFileIDs.split(",");
		for(var i=0;i<delIds.length;i++)
		{
			if( (fid+"") == (delIds[i]+"") )
			{
				return true;
			}
		}
		return false;
	}
	
	var confirmDelIndex = -1;
	var confirmDelId = -1;
	function removeExistFile()
	{
		var existFileAry = paramsAry[3];
		    existFileAry[confirmDelIndex] = "";
		    paramsAry[3] = existFileAry;

		if(delExistFileIDs.length > 0){
			delExistFileIDs = delExistFileIDs+","+confirmDelId;
		}else
			delExistFileIDs += confirmDelId;
		showExistFileList(paramsAry[0] , paramsAry[1] , paramsAry[2], paramsAry[3], paramsAry[4] ,paramsAry[5] ,paramsAry[6]);
	}
	
	function confirmRemoveExistFile(index, delId)
	{
		confirmDelIndex = index;
		confirmDelId = delId;
		_pop.showDialog("确认是否删除文件","","确认 | 取消","removeExistFile()");
	}
	
	function getExistFile()
	{
		if(delExistFileIDs == "")return delExistFileIDs;
		
		if(delExistFileIDs.charAt(delExistFileIDs.length-1) == ',')
			return delExistFileIDs.substring(0,delExistFileIDs.length-1);
		else
			return delExistFileIDs;
	}
	
	function setDelExistFile(val)
	{
		delExistFileIDs = val;
	}
	
//---------------Popup upload file end----------------------//


//---------------View Attachment ----------------------//
function getDownloadFilesStr(filenames,fileIDs,filetype,tbaseURL,foucedownload)  
	{
		try
		{
			var thisFile= filenames;
			var thisFileID= fileIDs;
			if(foucedownload == null){
				foucedownload = false;
			}
			
			if ( thisFile=="" )
			{
				return "";
			}
			else
			{
			
				eval("var allFile=[\"null\""+thisFile+"]");
				eval("var allFileID=[\"null\""+thisFileID+"]");
				var allFileStr = "";
				for(var f=1;f<allFile.length;f++)
				{
				    var sufix = allFile[f].substring(allFile[f].lastIndexOf(".")+1,allFile[f].length);
				    sufix = sufix.toLowerCase();
				     
					if(foucedownload){
		    	 		allFileStr+="<div style='margin-left:20px;margin-bottom:10px;width:800px; float:left; overflow:hidden;'>";
					}else{
		    	 		allFileStr+="<div style='margin-left:20px;margin-bottom:10px;width:260px; float:left; overflow:hidden;'>";
					}
 					var filePic = ["jpg","jpeg","gif","png","bmp","wbmp"];
				    var isPic = false;
				    for(var i = 0 ; i<filePic.length; i++){
				    	if(sufix==filePic[i]){
				    		isPic = true;
				    		break;
				    	}
				    }
				    
				    if(isPic){
						// allFileStr +="<td  width='100%' align=center>";
						var downloadurl = "";
						var cssclass = "workList_pic";
						if(foucedownload){
							downloadurl=tbaseURL+"/download?id="+allFileID[f]+"&type="+filetype;
							cssclass= "workList_pic_commodity";
						}else{
						 	downloadurl = tbaseURL +"/previewUploadFile?isImage=true&filetype="+filetype+"&fileid="+allFileID[f];
						}	
						allFileStr+="<div style=''><img border='0' src='"+tbaseURL+"/images/icon-clip.gif?v=201007121651' align='absmiddle'/> <a href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f]+"' target='_blank'>"+allFile[f].getSubstring(20)+"</a><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f]+"' target='_blank'><img class='"+cssclass+"' src='"+downloadurl +"' border='0' /></a></div>";
				    }else{
				     //	allFileStr +="<td  width='100%' align=left>";
						allFileStr+="<div style=''><img border='0' src='"+tbaseURL+"/images/icon-clip.gif?v=201007121651' align='absmiddle'/> <a href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f]+"' target='_blank'>"+allFile[f].getSubstring(20)+"</a><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f]+"' target='_blank'><img class='workList_pic_no' src='"+tbaseURL +"/previewUploadFile?isImage=false&filetype="+filetype+"&fileid="+allFileID[f]+"' border='0'/></a></div>";
				    }
					allFileStr+="</div>";
				}
				//allFileStr +="</div>";
				return allFileStr;
		 	}
	 	}
	 	catch(err)
	 	{
	 		return "";
	 	}
	}
	
	function clickImg_big_js(fileid,filetype){

		var imgSrc = "download?id="+fileid+"&type="+filetype;
		document.getElementById('imgDIV').innerHTML = '<img id="dialogImg" src="'+imgSrc+'" style="cursor:pointer;" onclick="clickImg_closeDialog_js(this)"></img>';
		var img = new Image();
		img.onload = function(){
			document.getElementById('imgDIV').style.width = this.width;
			document.getElementById('imgDIV').style.height = this.height;	
			dialog(previewPhoto,"id:imgDIV",(this.width+30)+"px",(this.height+70)+"px","id");	
		}
		img.src = imgSrc;
		
	}
		
	function clickImg_closeDialog_js(imgdialog){
			var imgSrc = imgdialog.src;
			var img = new Image();
			img.onload = function(){
				var height = img.height;
				$J("#floatBoxBg").animate({opacity:"0"},"normal",function(){$J(this).hide();});
				$J("#floatBox").animate({top:($J(document).scrollTop()-(height=="auto"?300:parseInt(height)))+"px"},"normal",function(){$J(this).hide();});
			}
			img.src = imgSrc;
		}
	
	
	function getPreviewImageStr(filenames,fileIDs,filetype,tbaseURL,foucedownload,useClickimg)  
	{
		try
		{
			var thisFile= filenames;
			var thisFileID= fileIDs;
			if(foucedownload == null){
				foucedownload = false;
			}
			if(null == useClickimg){
				useClickimg =  false;
			}
			
			if ( thisFile=="" )
			{
				return "";
			}
			else
			{
			
				eval("var allFile=[\"null\""+thisFile+"]");
				eval("var allFileID=[\"null\""+thisFileID+"]");
				var allFileStr = "";
				for(var f=1;f<allFile.length;f++)
				{
				    var sufix = allFile[f].substring(allFile[f].lastIndexOf(".")+1,allFile[f].length);
				    sufix = sufix.toLowerCase();
				     
					if(foucedownload){
		    	 		allFileStr+="<div style='margin-left:20px;margin-bottom:10px;width:800px; float:left; overflow:hidden;'>";
					}else{
		    	 		allFileStr+="<div style='margin-left:20px;margin-bottom:10px;width:260px; float:left; overflow:hidden;'>";
					}
 					var filePic = ["jpg","jpeg","gif","png","bmp","wbmp"];
				    var isPic = false;
				    for(var i = 0 ; i<filePic.length; i++){
				    	if(sufix==filePic[i]){
				    		isPic = true;
				    		break;
				    	}
				    }
				    var clickurl = tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f];
				    if(isPic){
						// allFileStr +="<td  width='100%' align=center>";
						if(useClickimg){
							clickurl="javascript:clickImg_big_js("+allFileID[f]+",\""+filetype+"\")";
						}
						var downloadurl = "";
						var cssclass = "workList_pic";
						if(foucedownload){
							downloadurl=tbaseURL+"/download?id="+allFileID[f]+"&type="+filetype;
							cssclass= "workList_pic_commodity";
						}else{
						 	downloadurl = tbaseURL +"/previewUploadFile?isImage=true&filetype="+filetype+"&fileid="+allFileID[f];
						}	
						allFileStr+="<div style=''><img border='0' src='"+tbaseURL+"/images/icon-clip.gif?v=201007121651' align='absmiddle'/> <a title='"+clickdown+"' href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f] +"' target='_blank'>"+allFile[f].getSubstring(20)+"</a><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='"+clickurl +"'><img title='"+clickpreview+"' class='"+cssclass+"' src='"+downloadurl +"' border='0' /></a></div>";
				    }else{
				     //	allFileStr +="<td  width='100%' align=left>";
						allFileStr+="<div style=''><img border='0' src='"+tbaseURL+"/images/icon-clip.gif?v=201007121651' align='absmiddle'/> <a title='"+clickdown+"' href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f]+"' target='_blank'>"+allFile[f].getSubstring(20)+"</a><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='"+tbaseURL +"/public/downloadFile.jsp?filetype="+filetype+"&fileid="+allFileID[f]+"' target='_blank'><img title='"+clickdown+"'  class='workList_pic_no' src='"+tbaseURL +"/previewUploadFile?isImage=false&filetype="+filetype+"&fileid="+allFileID[f]+"' border='0'/></a></div>";
				    }
					allFileStr+="</div>";
				}
				//allFileStr +="</div>";
				return allFileStr;
		 	}
	 	}
	 	catch(err)
	 	{
	 		return "";
	 	}
	}
	
//---------------View Attachment end----------------------//




  var GETBUYINGSTATUS_buyingid = 0;
  var _viewStatusObjId = "";
  var CALLBACK_FUNCTION = "";
   function setBuyingStatusValue(buyingid , viewStatusObjId,callbackfunction)
   {
   		GETBUYINGSTATUS_buyingid = buyingid;
   		_viewStatusObjId = viewStatusObjId;
   		CALLBACK_FUNCTION = callbackfunction;
   		sendRPC_getBuyingStatus();
   }
   
   function sendRPC_getBuyingStatus(){
   		//var sellerID = "<%=sellerID%>";
   		var rpcd = new RPCData();
		rpcd.reqData = "<Type>getBuyingStatusBySellerID</Type><Label>";
	    var data ="<currentBuyingID>"+GETBUYINGSTATUS_buyingid+"</currentBuyingID>"
	    //data+="<sellerID>" +sellerID+"</sellerID>";
	    data+= "</Label>";
		rpcd.reqData += data;
		rpcd.rpcPath = "PUBLIC_ACTION";
		rpcd.rpcCallback = "getBuyingStatusBySellerID_Callback(data)";
		callRPC(rpcd);	
			
	}
	
	var canShowConfirmReward = "false";
	var canShowDepositTip = "false";
	var showcordialtip = "false";
	
	function getBuyingStatusBySellerID_Callback(data){
	try{
		var dataDOM = XMLTools.parseXML(data);	
		var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");	
		if ( authorized=="false" )
		{
			sessionTimeOutAction();	
		}
		else
		{
		  	var success = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/success");
		   if(success == 'true')
		   {
			var statusValue = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusValue");
			var buyingType = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/buyingType");
			var isCloseBid = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/isCloseBid");//鏄惁涓烘殫鏍?
			var isThroughtBMH = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/isThroughtBMH");//鏄惁涓轰娇鐢ㄤ俊鎵?
			var curID = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/curID");
			var hadSellerDeposit = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/hadSellerDeposit");
		  
			var statusInnerHTML = "";
			
		  	 if(BuyingConstants.TYPE_STANDARD == buyingType.floatValue())
		  	 {
		  	 	if((isThroughtBMH == "true" && hadSellerDeposit == "true")|| statusValue.floatValue() > 12){
			 	 	
			 	 	statusInnerHTML = req_standard_status[statusValue.floatValue()-1];
			 	 
			 	 }else if(isThroughtBMH == "true" && hadSellerDeposit == "false"){
			 	 	
					statusInnerHTML = req_standard_status_no_seller_depoist[statusValue.floatValue()-1];
			 	 
			 	 }else{			 	 
			 	 	statusInnerHTML = req_standard_nothroughtbmh_status[statusValue.floatValue()-1];
			 	 }
			 	
				 canShowDepositTip = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/showdeposittip");
				 showcordialtip = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/showcordialtip");
				 var statusBuyerID = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusBuyerID");
				 var statusBuyerName = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusBuyerName");
				 
				 var statusSellerID = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusSellerID");
				 var statusSellerName = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusSellerName");
				 var statusIambuyer = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusIambuyer");
				 
				 var showCordialTip = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/showCordialTip");
				 var payDepositAmout = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/payDepositAmout");
				 var buyerName = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/buyerName");
				var haspaidtoseller = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/haspaidtoseller");
				 var sellerHadPaidDeposit = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/sellerHadPaidDeposit");//帮手已预存保证金
				 var sellerMustPaidDeposit = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/sellerMustPaidDeposit");//帮手需预存保证金
				 var buyerMustPaidDeposit = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/buyerMustPaidDeposit");//金主需预存保证金
				 var buyerHadPaidDeposit = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/buyerHadPaidDeposit");//金主已经预存保证金
				 var currencyName = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/currencyName");
				 var tradingdays = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/tradingdays");
				 var terminateDays = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/terminateDays");
				 canshowhelp = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/canshowhelp");
		
				 statusInnerHTML = statusIambuyer == "true" ? statusInnerHTML.replace("{7}" , msgd_seller) : statusInnerHTML.replace("{7}" , msgd_buyer) ;
 				 statusInnerHTML = statusIambuyer == "true" ? statusInnerHTML.replace("{8}" , "<a href='{6}' >{5}</a>") : statusInnerHTML.replace("{8}" , "<a href='{4}' >{3}</a>") ;
				  /*
				 	0:时间
					1:货币
					2:金额
					3:金主昵称
					4:金主链接
					5.帮手昵称
					6:帮手链接
					7:金主或帮手
					8:金主或帮手<a>模板
					9：已经支付金额
					10:需求完成天数
					11：金主已存保证金
					12：可终止交易时间
					13：帮手保证金链接
					14：需存金主保证金数
					15：金主保证金链接
					16：需存帮手保证金数
					17：帮手已经预存保证金
					18:预存诚意金
				 */
			
				 statusInnerHTML =  statusInnerHTML.replace("{3}" , "<font class='contentItem' ><u>"+statusBuyerName+"</u></font>");
				 statusInnerHTML =  statusInnerHTML.replace("{4}" , WebRoot+"/public/getMember.jsp?memberid="+statusBuyerID);
				 
				 statusInnerHTML =  replaceAllstr("{5}" , "<font class='contentItem' ><u>"+statusSellerName+"</u></font>",statusInnerHTML);
				 statusInnerHTML = replaceAllstr("{6}" , WebRoot+"/public/getMember.jsp?memberid="+statusSellerID, statusInnerHTML);
				 statusInnerHTML =  statusInnerHTML.replace("{10}" , tradingdays);
				 
				
				  	//alert(statusInnerHTML);
				  	if(buyerHadPaidDeposit != null && buyerHadPaidDeposit != undefined){
				 		statusInnerHTML =  statusInnerHTML.replace("{11}" , currencyName+" "+buyerHadPaidDeposit.currencyValue());
				 	}
				 	if(buyerMustPaidDeposit != null && buyerMustPaidDeposit != undefined){
				 			statusInnerHTML =  statusInnerHTML.replace("{14}" ,currencyName+" "+ buyerMustPaidDeposit.currencyValue());
				 	}
				 	statusInnerHTML =  statusInnerHTML.replace("{12}" , terminateDays);
				 	statusInnerHTML =  statusInnerHTML.replace("{13}" ,staticServer+"/help/zh_CN/content.php");
				 	statusInnerHTML =  statusInnerHTML.replace("{15}" ,staticServer+"/help/zh_CN/content.php");
					if(sellerMustPaidDeposit != null && sellerMustPaidDeposit != undefined){
				 		statusInnerHTML =  statusInnerHTML.replace("{16}" ,currencyName+" "+ sellerMustPaidDeposit.currencyValue());
				 	}
				 	
				 	if(sellerHadPaidDeposit != null && sellerHadPaidDeposit != undefined){
				 		statusInnerHTML =  statusInnerHTML.replace("{17}" , currencyName+" "+sellerHadPaidDeposit.currencyValue());
				 	}
					
				 
				if( haspaidtoseller != undefined && haspaidtoseller != null){
				 	statusInnerHTML =  statusInnerHTML.replace("{9}" , haspaidtoseller);
				 }
				 
				 if(statusValue == "1" && isThroughtBMH == "true" && showCordialTip == "true"){
				 	cordialmoneytip =  cordialmoneytip.replace("{3}" , "<font class='contentItem' ><u>"+statusBuyerName+"</u></font>");
					cordialmoneytip =  cordialmoneytip.replace("{4}" , WebRoot+"/public/getMember.jsp?memberid="+statusBuyerID);
				 	cordialmoneytip =  cordialmoneytip.replace("{18}" , payDepositAmout);
				 	statusInnerHTML += cordialmoneytip;
				 	
				 }
				 
			 }
			 else
			 if(BuyingConstants.TYPE_REWARD == buyingType.floatValue())
			 {
			 
			 	canShowConfirmReward = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/canShowConfirmReward");
			 	if(isCloseBid == "true"){
		
			 		statusInnerHTML = req_reward_status_closeBid[statusValue.floatValue()];//鏆楁爣
			 	}else{
			 		statusInnerHTML = req_reward_status[statusValue.floatValue()];
			 	}
			 //	var path = rootpath.replace("/cn","/");
	 		 	statusInnerHTML =  statusInnerHTML.replace("{3}" , "");
			
			 }

	 		 	var statusAmount = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusAmount");
		     	var statusExpirySecond = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/statusExpirySecond");
		  	 
			 statusInnerHTML =  statusInnerHTML.replace("{0}" , statusExpirySecond); // {0} must be expiry time
	
			 if(statusAmount != undefined || statusAmount != null)
		     {
		     	if(currencyName != undefined && currencyName != null){
					 statusInnerHTML =  replaceAllstr("{1}",currencyName,statusInnerHTML);
				}else{
					 statusInnerHTML =  replaceAllstr("{1}",bmh_currency[curID.floatValue()-1],statusInnerHTML);
				}
				 statusInnerHTML =  replaceAllstr("{2}",statusAmount.currencyValue(),statusInnerHTML);
			 }
			 
			
		   }
		   else
		   {
		   }
		
		}
		}catch(err){
			alert(err);
		}
		 try
			 {
			 	$("content_tradestatus").innerHTML = statusInnerHTML;
			 	CALLBACK_FUNCTION()
			 }
			 catch(err){
			 
			 }
			
			 setElementDisplay("statusBar", true);
   }
   
    function  replaceAllstr(s1, s2 , olds){
		var str="";	
		var arr=olds.split(s1);
		for(var n=0;n<arr.length-1;n++){
			str+=arr[n]+s2;
		}
		str+=arr[n];
		return str;
	}
	
	
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------GetCustomerDefaultCurrency-------------------------------------------------------------// 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	var curSelectID = "";
	var eventTemp ;
	function sendRPC_getCustomerDefaultCurrency(selectID,memberUrlTmp,callbackEvent)
	{
		var rpcd = new RPCData();
		curSelectID = selectID;
		eventTemp = callbackEvent;
        rpcd.reqData = "<Type>getCustomerDefaultCurrency</Type><Label>";
        rpcd.reqData +="</Label>";
        rpcd.rpcPath = "MEMBER_ACTION";
	    rpcd.rpcCallback = "getCustomerDefaultCurrency_Callback(data)";
	    callRPC(rpcd);
    }
    function getCustomerDefaultCurrency_Callback(data)
    {	
       var dataDOM = XMLTools.parseXML(data);
		var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");
		if ( authorized=="false" )
		{
			sessionTimeOutAction();
		}
	  else
	   {
			var respData = XMLTools.selectString(dataDOM, "//RPCResponse/ResponseData/Label/success");
			if(respData == "true")
			{
				
			 	var curID = XMLTools.selectString(dataDOM, "//RPCResponse/ResponseData/Label/curID");
			 	if(curID == 0)
			 		curID = 1;
				setSelect(curSelectID,curID);
				//$(curSelectID).value = curID;
				if(eventTemp != null)
					eventTemp();
			}

		}
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------End------------------GetCustomerDefaultCurrency-------------------------------------------------------------// 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//-------------------------------------------------------Open to-------------------------------------------------------------// 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	var _opentovalue ="";
    var morc ="";
    var opentToObjId = "";
	function popup_opentomember(_opentoobj)
	{
		opentToObjId = _opentoobj;
		var xmlstr = "";
		xmlstr += "<Data>";
		xmlstr += "<names>"+safeXMLChar($(opentToObjId).value)+"</names>";
		xmlstr += "<ids>"+_opentovalue+"</ids>";
		xmlstr += "</Data>";
			
		popuper.setTempXMLData(xmlstr);
		
		popuper.showPage(WebRoot+"/member/shared/specifyMembers.jsp" , "" , "opento_popupcallback()");
	}
      
	function opento_popupcallback()
	{
		var data = popuper.getCallBackXMLData();
		var opento = "";
		var opentoid = "";
		morc = data[0].type;
		if(data[0].type == 1)   //open to member
		{
			for(var i=1;i<data.length;i++)
			{
				opento += data[i].name +",";
				opentoid += data[i].id +",";
			}
			opento = opento.substring(0,opento.length-1);
			opentoid = opentoid.substring(0,opentoid.length-1);
			$(opentToObjId).value = safeHTMLChar(opento);
			_opentovalue = opentoid;
		}
		else
			if(data[0].type == 2)  // open to conditions
			{
				$(opentToObjId).value = data[1].conditions;
				_opentovalue =  data[1].conditions;
			}
	 }	
	 
	 function  setOpentoMembersId( _vals )
	 {
	 	_opentovalue = _vals;
	 }
	 
	 function  getOpentoMembersId()
	 {
	 	return _opentovalue;
	 }
//-------------------------------------------------------End Open to-------------------------------------------------------------// 	
	

//-------------------------------------------------------Ask question-------------------------------------------------------------// 	
	function askQuestion()
	{	
		popuper.showPage(WebRoot+"/shared/askQuestion.jsp");
	}
	
//---------------- Event Action for List table create by div --------------------------
	var clickField=null;
	function onMouseOver(obj)
	{
		if(clickField==null||clickField!=obj)
		{
			obj.style.background="#E0E0E0";
		}
	}
	function onMouseOut(obj)
	{
		if(clickField==null||clickField!=obj)
		{
			obj.style.background="";
		}
	}	
	function onMouseClick(obj)
	{
		if(clickField!=null)
		{
			clickField.style.background="";
		}
		clickField = obj;
		obj.style.background="#FDEAB7";
		setData(obj);// You need to implement setData yourself.
	}
	
	var friendOrBlack = 1;
	
	function addAsFriend(memberID){
		friendOrBlack = 1;
		moveFriend(1,memberID);
	}
	
	function addToBlackList(memberID){
		friendOrBlack = 2 ;
		moveFriend(2,memberID);
	}
	
	function moveFriend(groupId,memberID){
	
		var rpcd = new RPCData();
        rpcd.reqData = "<Type>moveMember</Type><Label>";
        rpcd.reqData += "<moveTo>"+groupId+"</moveTo>";
        rpcd.reqData += "<memberID>"+memberID+"</memberID>";
        rpcd.reqData +="</Label>";
        rpcd.rpcPath = "MEMBER_ACTION";
	    rpcd.rpcCallback = "moveMember_Callback(data)";
	    callRPC(rpcd);
	}
	
	function moveMember_Callback(data){
	 	var dataDOM = XMLTools.parseXML(data);
		var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");
		if ( authorized=="false" )
		{
			sessionTimeOutAction();
		}
		else
		{
			var msg = "";
			if(friendOrBlack == 1 ){
				msg = page_label_200038;
			}else{
				msg = page_label_200180;
			}
			var respData = XMLTools.selectString(dataDOM, "//RPCResponse/ResponseData/Label/success");
			if(respData == "true")
			{
				try{
					popuper.showMsg(msg,"","",1);
				}catch(err){
					popupPage.showMsg(msg,"","",1);
				}
	 
			}

		}

	}
	
			
	function initMouseEvent(targetDivName){
		var divObjs =document.getElementsByTagName('div');
	    for(var i=0; i<divObjs.length; i++)
	    {
	        if(divObjs[i].getAttribute("name") == targetDivName)
	        {
	        	(
	        		function (obj)
	        		{
	        			obj.onmouseover = function(){
				            onMouseOver(obj);
				        }
	        			obj.onmouseout = function(){
				            onMouseOut(obj);
				        }
	        			obj.onclick = function(){
				            onMouseClick(obj);
				        }
	        		}
	        	)(divObjs[i]);
	            
	        }
	    }
	}
	
// --------------------- End -----------------------

function openChangeNickName(nickname){
	var toUrl = WebRoot+'/member/secure/changeNickName.jsp?o='+encodeURI(nickname);

	popuper.showPage(toUrl,common_label_changeNickname,"","location.reload();");
}	

function searchForIndex(){
	var bmhEntity = $("searchType").value;
	var keyword = $("search_keyword").value;
	keyword=URIEncode(keyword);
	if( keyword == "" ){
		popuper.showMsg(common_search_input_keyword+"!","",'',2);
		return;
	}
	var param = "bmhEntity="+bmhEntity+"&keyword="+keyword+"&expiryDate=&offerMin=&offerMax=&locationId=&pageNo=1&epageNum=10";
	window.open(WebRoot+"/public/advSearch.jsp?"+param);
}
function searchForTopBar(dType,params){
	//dType: ALL,BUYING,SERVICE,SOLUTION,ENDOWMENT
	//var param = "bmhEntity="+dType+"&keyword=&expiryDate=&offerMin=&offerMax=&locationId=&pageNo=1&epageNum=10";
	window.open(WebRoot+"/public/"+dType+".jsp"+ ((params != null && params != "" && params != "null" )? "?"+params : "") );
}
function zoomIn(desc_id)
{
		popuper.showPage(WebRoot+'/shared/zoomIn.jsp?descid='+desc_id+'&timestr='+(new Date()).getTime(),zoom_in,'');
}

//-----------------------------------Get lastest member detail ------------------------//
var _updateMemberDetailEvent = null;
function sendRPC_getMemberDetail(callbackEvent)
{
	var rpcd = new RPCData();
	_updateMemberDetailEvent = callbackEvent;
	rpcd.reqData = "<Type>getMemberDetail</Type><Label>";
	rpcd.reqData += "</Label>";
	
	rpcd.rpcPath = "MEMBER_ACTION";
	rpcd.rpcCallback = "getMemberDetail_callback(data)";
	callRPC(rpcd);
}

  function getMemberDetail_callback(data)
  {
     var dataDOM = XMLTools.parseXML(data);	
	 var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");	
	 if ( authorized=="false" )
	  {
		sessionTimeOutAction();	
	  }else{
        var respData = XMLTools.selectString(dataDOM, "//RPCResponse/ResponseData/Label/success");
	    if ( respData == 'true')
		{   
			var	nodes = dataDOM.selectNodes("//RPCResponse/ResponseData/Label/member");
			var datas = XMLTools.recordsFromXML(nodes);
			
			var _member = datas[0];
			//nickName email emailVerify newEmail
			try
			{
				_updateMemberDetailEvent(_member);
			}
			catch(err)
			{}
			
		}else{
		   var res = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label");
		   popuper.showMsg(res,'','popupPage.closePage()',0);
		}
		}
}
//-----------------------------------Get lastest member detail ---------------End---------//

		
//-----------------------------------------------------------------------发送邮件激活-------------------------------------------------------------------------------//
function sendRPC_sendActiveEmail(){
	var rpcd = new RPCData();
	rpcd.reqData = "<Type>sendActiveEmail</Type><Label>";
	rpcd.reqData += "<memberID>"+currentLoginID+"</memberID>";
	rpcd.reqData += "</Label>";
	rpcd.rpcPath = "PUBLIC_ACTION";
	rpcd.rpcCallback = "sendActiveEmail_Callback(data)";
	callRPC(rpcd);
}


 function sendActiveEmail_Callback(data)
 {

    var dataDOM = XMLTools.parseXML(data);	
	var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");	
	if ( authorized=="false" )
	{
		sessionTimeOutAction();	
	}
	else
	{
	   var success = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/success");
	   
	   if(success == 'true')
	   {
	     popuper.showMsg(send_member_active_email_success,"","",1);
	     try
	     {
	     	updateMemberDetailEvent(); // define in include_ActiveEmailTips
	     }catch(err)
	     {}
	   }
	   else
	   {
	   		 var err = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label");
	   		 if(err != "" && err != "null"){
	    	 	//popuper.showMsg(err,"","",0);
	    	 }
	   }
	} 
}

 function setBeneficenceDetail_Buyer(record)
   {
   		
		$("subject").innerHTML = (record.subject=="null")?record.detail.substring(0,20):record.subject;
		$("desc").innerHTML = record.detail;
		$("content_reqid").innerHTML = record.id;
	 
		$("content_amount").innerHTML = record.currencyName+" "+record.endowmentAmount.currencyValue();
  		$("content_createdate").innerHTML = DateFormat.toLocaleString(record.createDt);
  		$("content_finishdate").innerHTML = DateFormat.toLocaleString(record.expiryDate);
  		
	    if(record.countryname == "" || record.countryname == "null")
	  	    $("content_area").innerHTML = common_area_anywhere;
	    else
		    $("content_area").innerHTML = areaFormat( record.countryname , record.statename , record.cityname);

  		$("content_trueName").innerHTML = record.trueName;
  		$("content_address").innerHTML = record.address;
  		$("content_birthday").innerHTML = (record.birthday=="null")?"--":record.birthday;
  		$("content_gender").innerHTML = common_gender_list[record.gender-1];
  		$("content_tel").innerHTML = record.telNo;
  		$("content_customBankName").innerHTML = record.paymentMethodName;
  		$("content_accountNo").innerHTML = record.accountNo;
  		$("content_holder").innerHTML = record.holder;
  		$("content_yes").innerHTML = common_system_state_yesorno[0];
  		setElementDisplay("membertypeTR",record.accounttype == "1");
		if(!(record.hadOver.toBoolean())){
			$("moreendowment").style.display = "";
		}
  		$("content_endowmentTotalAmount").innerHTML = record.currencyName+" "+record.endowmentTotalAmount.currencyValue();
  		$("content_withdrawTotalAmount").innerHTML = record.currencyName+" "+record.withdrawTotalAmount.currencyValue();
  		if( record.withdrawTotalAmount > 0 )
  		{
  			$("withdrawRecord_url").href = "member/beneficence/endowmentWithdraw.jsp?endowmentId="+record.id;
  			$("url_viewWithdrawRecord").style.display="";
  			
  		}
  		
  		$("content_endowmentMoreAmount").innerHTML = record.currencyName+" "+record.endowmentMoreAmount.currencyValue();
  		$("content_withdrawServiceAmount").innerHTML = record.currencyName+" 0.02";
  		if(record.endowmentStatus == "3"){
  			$("pauseTR").style.display = "";
  			$("normalTR").style.display = "none";
  		}else {
  			$("pauseTR").style.display = "none";
  			$("normalTR").style.display = "";
  		}
	
   }
   
     
   function setBeneficenceDetail_Seller(record)
   {
  		$("raisedBy").innerHTML = Trim(record.memberName,false);
		
		$("subject").innerHTML = (record.subject=="null")?record.detail.substring(0,20):record.subject;
		$("desc").innerHTML = record.detail;
		$("content_reqid").innerHTML = record.id;
	 
		$("content_amount").innerHTML = record.currencyName+" "+record.endowmentAmount.currencyValue();
  		$("content_createdate").innerHTML = DateFormat.toLocaleString(record.createDt);
  		$("content_finishdate").innerHTML = DateFormat.toLocaleString(record.expiryDate);
  		
	    if(record.countryname == "" || record.countryname == "null")
	  	    $("content_area").innerHTML = common_area_anywhere;
	    else
		    $("content_area").innerHTML = areaFormat( record.countryname , record.statename , record.cityname);

  		$("content_trueName").innerHTML = record.trueName;
  		$("content_address").innerHTML = record.address;
  		$("content_birthday").innerHTML = (record.birthday=="null")?"--":record.birthday;
  		$("content_gender").innerHTML = common_gender_list[record.gender-1];
  		$("content_tel").innerHTML = record.telNo;
  		$("content_customBankName").innerHTML = record.paymentMethodName;
  		$("content_accountNo").innerHTML = record.accountNo;
  		$("content_holder").innerHTML = record.holder;
  		$("content_yes").innerHTML = common_system_state_yesorno[0];
  		setElementDisplay("membertypeTR",record.accounttype == "1");
  		try{
		if(!(record.hadOver.toBoolean())){
			$("moreendowment").style.display = "";
		}
  		$("content_endowmentTotalAmount").innerHTML = record.currencyName+" "+record.endowmentTotalAmount.currencyValue();
  		$("content_withdrawTotalAmount").innerHTML = record.currencyName+" "+record.withdrawTotalAmount.currencyValue();
  		if( record.withdrawTotalAmount > 0 )
  		{
  			$("withdrawRecord_url").href = "endowmentWithdraw.jsp?endowmentId="+record.id;
  			$("url_viewWithdrawRecord").style.display="";
  	
  		}
  		
  		$("content_endowmentMoreAmount").innerHTML = record.currencyName+" "+record.endowmentMoreAmount.currencyValue();
  		$("content_withdrawServiceAmount").innerHTML = record.currencyName+" 0.02";
		}catch(err){
		
		}
		
		if(record.endowmentStatus == "3"){
  			$("pauseTR").style.display = "";
  			$("normalTR").style.display = "none";
  		}else {
  			$("pauseTR").style.display = "none";
  			$("normalTR").style.display = "";
  		}
}
//-----------------------------------------------------------------------发送邮件激活  End----------------------------------------------------------------------------------//
	
	function sendRPC_authOperationForCommodity(operation,postId,callback,refreshPage){
		var rpcd = new RPCData();
		rpcd.reqData = "<Type>authOperationForCommodity</Type><Label>";
        rpcd.reqData += "<operation>"+operation+"</operation>";
        rpcd.reqData += "<postID>"+postId+"</postID>";
        rpcd.reqData += "</Label>";
        rpcd.rpcPath = "TRADING_STATUS_ACTION";
	    rpcd.rpcCallback = "authOperation_callback(data)";  //update file list
	    rpcd.vars.push(callback);
	    rpcd.vars.push(refreshPage);
	    callRPC(rpcd);
	}
			
		
	function sendRPC_authOperation(operation,postId,memberID,postType,callback,refreshPage){
		var rpcd = new RPCData();
		rpcd.reqData = "<Type>authOperationForTrading</Type><Label>";
        rpcd.reqData += "<operation>"+operation+"</operation>";
        rpcd.reqData += "<postType>"+postType+"</postType>";
        rpcd.reqData += "<postID>"+postId+"</postID>";
        if(postType == "1"){
        	rpcd.reqData += "<memberID>"+memberID+"</memberID>";
        }else if(postType == "2"){
        	rpcd.reqData += "<traMsgID>"+memberID+"</traMsgID>";
        }else{
        	rpcd.reqData += "<cardTradingID>"+memberID+"</cardTradingID>";
        }
        rpcd.reqData += "</Label>";
        rpcd.rpcPath = "TRADING_STATUS_ACTION";
	    rpcd.rpcCallback = "authOperation_callback(data)";  //update file list
	    rpcd.vars.push(callback);
	    rpcd.vars.push(refreshPage);
	    callRPC(rpcd);
	}
	
	
	function authOperation_callback(data,rpcd){
	 	var dataDOM = XMLTools.parseXML(data);	
		var authorized = XMLTools.selectString(dataDOM, "//RPCResponse/Authorized");	
		if ( authorized=="false" )
		{
			sessionTimeOutAction();	
		}
		else
		{
		   	var success = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/success");
		 	try{
			   if(success == 'true')
			   {
			   		var canoperation = XMLTools.selectString(dataDOM,"//RPCResponse/ResponseData/Label/canoperation");
			   	
				   		if(canoperation == "false"){
				   			eval(rpcd.vars[1]+"()");
				   		}else{
				   			eval(rpcd.vars[0]+"()");
				   		}
				   
			   }
			   else
			   {
			   		eval(rpcd.vars[1]+"()");
			   }
		   	}catch(err){
		   		alert(err);
			}
	} 
	}
		
		// set requestList.jsp serviceList.jsp solutionList.jsp title
		function setTitle()
		{
			var temp_title="";
			for(var i=100;i>0;i--)
			{
				if(document.getElementById("selectCate_"+i) == null)continue;
				if(document.getElementById("selectCate_"+i).value=="0")continue;
				var cateObj = document.getElementById("selectCate_"+i);
				temp_title += cateObj.options[cateObj.selectedIndex].text+" - ";
			}
			document.title = temp_title+document.title;
		}

var searchHeight=0;
var time;
var timeP = 8;
var isInit = false;
			
function show_gjSearDiv(value){

	try
	{
	showAreaChoose("areaDiv");
	isInit=true;
	}catch(e)
	{
	}
	searchHeight=0;
	time=setInterval(
		function(){
			searchHeight+=timeP;
			if(searchHeight >= value){
				searchHeight = value;
				window.clearInterval(time);
			}
			$("gj_searchDiv").style.height=searchHeight+"px";
		},5
	);
}

function none_gjSearDiv(value){
	searchHeight = value;
	isInit = false;
	time=setInterval(
		function(){
			searchHeight-=timeP;
			if(searchHeight<=0){
				searchHeight=0;
				window.clearInterval(time);
			}
			$("gj_searchDiv").style.height=searchHeight+"px";
		},5
	);
}

function search()
{
	var searchType = getRadioValue("searchDio");

	var minOffer = $("offerMin").value;
	var maxOffer = $("offerMax").value;
	var locationId = "0";
	if(isInit)
	{	
		var tempLoc = getAreaArrayVal();
		var locationId = tempLoc[0];
		
		if( tempLoc[1]!=0 )
		{
			locationId = tempLoc[1];
		}
		
		if( tempLoc[2]!=0 )
		{
			locationId = tempLoc[2];
		}

	}
	
	var keyword = $("keyword").value;
		
	if( keyword == "" )
	{
		popuper.showMsg(common_search_input_keyword+"!","",'',2);
		return;
	}
	
	var time = $("timeSelect").value+$("timeText").value;
	
	doSearch(searchType,keyword,time,minOffer,maxOffer,locationId,"1","10");
}
function doSearch(bmhEntity,keyword,expiryDate,offerMin,offerMax,locationId,pageNo,epageNum)
{
	if( pageNo==null ) pageNo="1";
	var param = "bmhEntity="+bmhEntity+"&keyword="+keyword+"&expiryDate="+expiryDate+"&offerMin="+offerMin+"&offerMax="+offerMax+"&locationId="+locationId+"&pageNo="+pageNo+"&epageNum="+epageNum;
	window.open(WebRoot+"/public/advSearch.jsp?"+param);
}
function Helper_Class(){
		var _T = this;
		_T.add = function(objid, text, link, target, xvar, yvar){
			var o=document.getElementById(objid);
			if(!o){return;}
			var newa = document.createElement("a");
			newa.href = link;
			newa.target=target;

			var newo=document.createElement("img");
			newo.src=staticServer+"/images/question.gif"
			newo.title=text;
			newo.alt=text;
			newo.style.position="relative";
			newo.style.cursor="pointer";
			newo.style.border="0px";
			newo.style.left = xvar+"px";
			newo.style.top = yvar+"px";
			newa.appendChild(newo);
			o.appendChild(newa);
		}
}

var Helper = new Helper_Class();
